gpt4 book ai didi

android - 如何以编程方式设置(文本) View 属性?

转载 作者:太空狗 更新时间:2023-10-29 16:25:10 27 4
gpt4 key购买 nike

我拼命地尝试以编程方式设置表格中单元格的 TextView 属性,但无法让它工作!每当我设置布局属性时,该字段将不会出现(但不会给出任何错误或异常)。我将其归结为这个简单的示例:

package mmo.application.listpro;

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class Test extends Activity
{
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

TableLayout table = new TableLayout(this);
TableRow row = new TableRow(this);
for (String label: new String[] {"field1", "field2", "field3"}) {
TextView tv = new TextView(this);
tv.setText(label);
// LinearLayout.LayoutParams lp =
// new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
// LinearLayout.LayoutParams.WRAP_CONTENT);
// lp.setMargins(2, 2, 2, 2); // left/top/right/bottom
// tv.setLayoutParams(lp);
row.addView(tv);
}
table.addView(row);
setContentView(table);
}
}

这将显示三个字段,但是当您取消对五个注释行的注释时,将显示 NOTHING。为什么会这样?为什么设置布局参数会导致我的 TextView 不显示?我卡住了!我错过了什么?

迈克尔

PS.: 这是 list ,如果有好心人想快速尝试一下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="mmo.application.listpro" android:versionCode="1" android:versionName="Development">
<application
android:icon="@drawable/icon"
android:label="@string/app_name"
android:debuggable="true">
<activity
android:label="test"
android:name=".Test"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:targetSdkVersion="8" android:minSdkVersion="8" />
</manifest>

最佳答案

TableRow 始终强制这些值分别为 MATCH_PARENT 和 WRAP_CONTENT。因此,您只需创建默认的 TableRow.LayoutParams,设置边距并将其应用于 TextView。

TableRow.LayoutParams lp = new TableRow.LayoutParams();
lp.setMargins(2, 2, 2, 2);
row.addView(tv, lp);;

关于android - 如何以编程方式设置(文本) View 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3696843/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com