我使用此代码更改颜色,但只有当我退出应用程序并再次运行时,颜色才会更改。如何决定立即更改颜色?
adapter2 = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1, list) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView text = (TextView) view
.findViewById(android.R.id.text1);
text.setTextColor(Color.parseColor(color));
return view;
}
};
答案 0 :(得分:4)
创建res/color/button_text.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:color="#ffff0000"/> <!-- pressed -->
<item android:state_focused="true"
android:color="#ff0000ff"/> <!-- focused -->
<item android:color="#ff000000"/> <!-- default -->
</selector>
此布局XML
会将颜色列表应用于View
:
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textColor="@color/button_text" />
如果您想动态应用State Color
,那么
ColorStateList myColorStateList = new ColorStateList(
new int[][]{
new int[]{android.R.attr.state_pressed}, //1
new int[]{-android.R.attr.state_focused}, //2
new int[]{android.R.attr.state_selected, android.R.attr.state_pressed} //3
},
new int[] {
Color.RED, //1
Color.WHITE, //2
Color.BLUE //3
}
);
title_txt.setTextColor(myColorStateList);
有关详情,请访问:http://developer.android.com/guide/topics/resources/color-list-resource.html
答案 1 :(得分:4)
将此文件放在res / color文件夹中textselector_list.xml
<?xml version="1.0" encoding="utf-8"?>
<item android:state_pressed="true" android:color="#FFFFFFFF"/>
<!-- pressed -->
<item android:state_focused="true" android:color="#FFFFFFFF"/>
<!-- focused -->
<item android:state_selected="true" android:color="#FFFFFFFF"/>
<!-- selected -->
<item android:color="#FF888888"/>
<!-- default -->
并将其设置为android:textColor="@color/textselector_list"
listView
项,即TextView
或Button
。