Java 在android.R.layout.simple\u list\u item\u 2中更改文本颜色
我正在使用一个简单的适配器来显示我的代码。不幸的是,我需要更改顶部文本视图的颜色 这是我的代码片段:Java 在android.R.layout.simple\u list\u item\u 2中更改文本颜色,java,android,xml,simpleadapter,Java,Android,Xml,Simpleadapter,我正在使用一个简单的适配器来显示我的代码。不幸的是,我需要更改顶部文本视图的颜色 这是我的代码片段: // 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,
// 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);
我试图创建自己的简单列表项,但由于某种原因,它不允许我更改xml中文本视图的颜色。有什么办法吗
我最后的想法是:
findViewById(android.R.id.text1).setTextColor(#000)
但是我不知道放在哪里,我的十六进制代码不起作用。为你的列表视图
项目创建一个自定义xml布局,并使用textColor
属性设置文本视图
的文本颜色:
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textColor="#ff0000" />
您必须从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;
};
};
您应该使用
setTextColor(Color.any Color)代码>
如果使用微调器下拉列表,文本颜色将不会更改。要进行更改,我们还必须添加上述方法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;
}
要传递十六进制颜色,必须使用setTextColor(color.parseColor(“#YOURCOLOR”)
。但是,如果没有自定义适配器,这将无法工作。这真的很奇怪@jaimin。如果你发布一个新问题来解释你的问题会更好。我认为这不是一个好的解决方案。您不应该将应用程序逻辑与样式混合使用。最好按照@FD_uu的建议定义一个自定义布局。@Jeremy,里面没有什么错。如果它是错误的,那么就不会有方法setTextColor
。您不应该将应用程序逻辑与样式混为一谈,这是您的观点。你介意解释一下为什么错了吗?@Jeremy如果你用colors.xml中定义的颜色替换Color.RED,你又得到了关注点的分离。今天运行良好,在Android 5、6和8上测试,Taarget SDK 28,Android Studio 3.1.3=)非常感谢
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;
}