简体   繁体   中英

Change text color in android.R.layout.simple_list_item_2

I'm using a simple adapter to display my code. Unfortunately, I need to change the top textView color.

This is a snippet of my code:

// 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);

I tried to make my own simple_list_item_2, but it wouldn't allow me to change the color of a textView in xml for some reason. Any ideas on how to do this?

My last thought is:

findViewById(android.R.id.text1).setTextColor(#000) but I don't know where to put it, and my hex code doesn't work.

you have to override getView from SimpleAdapter. For instance:

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;
        };
    };

Create a custom xml Layout for your ListView items and set the text color of the TextView using the textColor attribute:

<TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView"
            android:textColor="#ff0000" />

If you use a Spinner dropdown text color will not change. To change we must also add the above method the method 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; 
             }

You should use setTextColor(Color.any color);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM