在Android中更改文本颜色:android.R.layout.simple_list_item_2

9

我正在使用一个简单的适配器来显示我的代码。不幸的是,我需要更改顶部textView的颜色。

这是我的一小段代码:

// Keys used in Hashmap
String[] from = { "txt1", "txt2" };
// Ids of views in listview_layout
int[] ids = { android.R.id.text1, android.R.id.text2 };
SimpleAdapter adapter = new SimpleAdapter(this, aList,
android.R.layout.simple_list_item_2, from, ids);
setListAdapter(adapter);

我尝试制作自己的simple_list_item_2,但无法在xml中更改textView的颜色。您有什么想法吗?
我的最后一个想法是:findViewById(android.R.id.text1).setTextColor(#000),但我不知道将其放在哪里,而且我的十六进制代码不起作用。

要传递一个十六进制颜色,您必须使用setTextColor(Color.parseColor(“#YOURCOLOR”))。但是,在没有自定义适配器的情况下,这将无法工作。 - FD_
4个回答

19
你需要从SimpleAdapter覆盖getView方法。例如:
SimpleAdapter adapter = new SimpleAdapter(this, aList,
            android.R.layout.simple_list_item_2, from, ids) {

        public View getView(int position, View convertView, ViewGroup parent) {
            View view = super.getView(position, convertView, parent);
            TextView text1 = (TextView) view.findViewById(android.R.id.text1);
            text1.setTextColor(Color.RED);
            return view;
        };
    };

这真的很奇怪,@jaimin。如果您发布一个新问题来解释您的问题会更好。 - Blackbelt
1
我认为这不是一个好的解决方案。你不应该将应用逻辑与样式混合在一起。最好按照@FD_的建议定义一个自定义布局。 - Jeremy
1
@Jeremy,这里没有任何问题。如果有问题的话,就不会有setTextColor方法了。你不应该将应用逻辑与样式混合在一起,这只是你的观点。您介意解释一下为什么这是错误的吗? - Blackbelt
2
@Jeremy 如果你将Color.RED替换为在colors.xml中定义的颜色,你就可以再次实现关注点分离。 - WarrenFaith
1
今天工作正常,已在Android 5、6和8上进行了测试,目标SDK为28,使用的是Android Studio 3.1.3 =) 非常感谢。 - Marcus J.Kennedy
显示剩余6条评论

1
创建一个自定义的xml布局,用于ListView的项,并使用textColor属性设置TextView的文本颜色:
<TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView"
            android:textColor="#ff0000" />

0
如果您使用Spinner下拉菜单,文本颜色将不会改变。要更改颜色,我们还必须添加上述方法getDropDownView。
public View getDropDownView (int position, View convertView, ViewGroup parent) {
                 View view = super.getDropDownView (position, convertView, parent); 
                 TextView text = (TextView) view.findViewById (android.R.id.text1); 
                 text.setTextColor (Color.BLACK); 
                 return view; 
             }

-1

你应该使用 setTextColor(Color.任意颜色);

TextView txt = (TextView) view.findViewById(R.id.text1);
txt.setTextColor(Color.yellow);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接