Android – change the text color of listview items

How to change the text color of the item added to the listview. I need to change the color programmatically in the code according to some conditions, and change different lines to different text colors (for example, line 0 = red, line 1 = white, line 3 = blue, etc.). Setting the text color in the XML layout will not meet my requirements. This is my code:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listview);

    setlistadapter(new ArrayAdapter<String>(ListViewEx.this,
            R.layout.list_item_1, Global.availableDecks));

//something like this 
//listview.getPosition(0).setTextColor(red);
//listview.getPosition(1).setTextColor(white);
//listview.getPosition(2).setTextColor(blue);

And my XML:

    <?xml version="1.0" encoding="utf-8"?>


    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/label"
    android:layout_width="match_parent"
    android:layout_height="35dp"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:textSize="30px"
    android:layout_marginLeft="5px"
    android:singleLine="true"
   />

resolvent:

Implement your own arrayadapter and override the getview () method:

    public class Adapter1 extends ArrayAdapter<String> {

    public Adapter1(Context context, int resID, ArrayList<String> items) {
        super(context, resID, items);                       
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = super.getView(position, convertView, parent);
        if (position == 1) {
            ((TextView) v).setTextColor(Color.GREEN); 
        }
        return v;
    }

}

Don't forget to provide an alternative else clause to set the color to the default color, so that you have no problem when dealing with circular rows. Then in your activity:

setlistadapter(new Adapter1(ListViewEx.this,
            R.layout.list_item_1, Global.availableDecks));

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>