我有一个列表视图,其中每个项目都在custom_row_views.xml中定义:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/showtitle"
android:textSize="17sp"
android:textStyle="bold"
android:textColor="#FFFF00"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView android:id="@+id/showdate"
android:textSize="14sp"
android:textStyle="italic"
android:textColor="#CCCCCC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView android:id="@+id/showsummary"
android:textSize="17sp"
android:textStyle="normal"
android:textColor="#FFFFFF"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
请注意,这三个文本视图具有不同的文本颜色。
现在,根据偏好设置中的一个设置,用户应该能够更改文本视图项的文本颜色。
基本上,我看到有两种方法可以做到这一点。其中一种是使用主题:
<resources>
<style name="ThemeBlack" parent="@android:style/Theme">
<item name="android:textColor">#FFFFFF</item>
<item name="android:typeface">sans</item>
<item name="android:background">#999999</item>
<item name="android:textSize">16sp</item>
</style>
<style name="ThemeRed" parent="@android:style/Theme">
<item name="android:textColor">#0000FF</item>
<item name="android:typeface">sans</item>
<item name="android:background">#c81111</item>
<item name="android:textSize">16sp</item>
</style>
</resources>
例如,在onCreate()方法中:
this.setTheme(R.style.ThemeRed);
这里的问题在于它将所有textview的文本颜色更改为定义在样式中的颜色。换句话说,它们不再有所不同。因此,我的第一个具体问题是:
是否可以以某种方式定义或应用样式,使其适用于具有三个不同颜色文本视图的listview?
另一种方法是通过编程设置文本颜色,而不是使用样式和主题。这是我的第一种方法,我认为它很容易,但我已经苦苦挣扎了几个小时却无济于事。
我已经尝试在ListActivity的onCreate中执行以下操作:
TextView tv = (TextView) findViewById(R.id.showsummary);
tv.setTextColor(Color.RED);
但这会导致应用程序崩溃。
然后我尝试了这个:
TextView tv = null;
LayoutInflater inflater = this.getLayoutInflater();
View aView = inflater.inflate(R.layout.custom_row_view, null);
tv = (TextView) aView.findViewById(R.id.showsummary);
tv.setTextColor(Color.RED);
它不会崩溃,但也不起作用!
因此,我的第二个问题是:
如何在代码中更改列表视图项的文本颜色?
请注意,所有列表视图项都应具有新颜色;重要的是三个单独的文本视图内部的项目应分别着色。换句话说,我不是要设置列表视图中单个项目的颜色。
更新: 我不知道是否有任何区别,但这是如何弹出列表视图的:
Cursor showsCursor = mDbHelper.fetchSummaries(mCategory);
String[] from = new String[]{C2CDbAdapter.SUMMARY_TITLE, C2CDbAdapter.SUMMARY_DATE, C2CDbAdapter.SUMMARY_SUMMARY};
int[] to = new int[]{R.id.showtitle, R.id.showdate, R.id.showsummary};
SimpleCursorAdapter shows = new SimpleCursorAdapter(this, R.layout.custom_row_view, showsCursor, from, to);
setListAdapter(shows);