我目前正在用外部来源的数据填充 TableLayout。以编程方式创建 TableRows 和 TextViews 后,它们的文本颜色设置为白色(似乎是默认值)。
我知道我可以使用 myTextView.setTextColor(Color.BLACK);
设置颜色,但我正在寻找一种在 XML 布局文件中定义颜色的方法 (我想将视觉效果与逻辑分开)。有谁知道如何做到这一点?
我的布局(充满示例行):
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="@+id/mytable"
android:stretchColumns="0,1,2"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
style="@style/AppTheme" >
<TableRow>
<TextView android:text="field1" />
<TextView android:text="field2" />
<TextView android:text="field3" />
</TableRow>
</TableLayout>
我的java代码:
public void updateTable() {
TableLayout table = (TableLayout) findViewById(R.id.mytable);
table.removeAllViewsInLayout();
TableRow row = new TableRow(getApplicationContext());
TextView text;
// Add Heading
text = new TextView(getApplicationContext());
text.setText("Head1");
text.setTextColor(this.textColor);
row.addView(text);
text = new TextView(getApplicationContext());
text.setText("Head2");
text.setTextColor(this.textColor);
row.addView(text);
text = new TextView(getApplicationContext());
text.setText("Head3");
text.setTextColor(this.textColor);
row.addView(text);
table.addView(row);
for(Data d : this.getData()) {
TableRow r = new TableRow(getApplicationContext());
TextView t1 = new TextView(getApplicationContext());
TextView t2 = new TextView(getApplicationContext());
TextView t3 = new TextView(getApplicationContext());
t1.setTextColor(this.textColor);
t2.setTextColor(this.textColor);
t3.setTextColor(this.textColor);
t1.setText(d.getData1());
t2.setText(d.getData2());
t3.setText(d.getData3());
r.addView(t1);
r.addView(t2);
r.addView(t3);
table.addView(r);
}
}
最佳答案
创建一个 styles.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyTheme" parent="android:Theme">
<item name="android:textViewStyle">@style/MyTextViewStyle</item>
</style>
<style name="MyTextViewStyle" parent="android:Widget.TextView">
<item name="android:textColor">#F00</item>
<item name="android:textStyle">bold</item>
</style>
</resources>
然后只需将该主题应用到您在 AndroidManifest.xml 中的应用程序:
<application […] android:theme="@style/MyTheme">…
关于android - 如何在 Android 布局中定义所有子项的文本颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37297066/