Change text color for ListView items

微笑、不失礼 提交于 2019-12-01 20:57:32

问题


How do I change the text color for the items that are added to a ListView. I need to change the colors programmatically in code based on certain conditions and changing different rows to different text colors(e.g. row 0 = red, row1= white, row3= blue etc). Setting a text color in the xml layout will not meet my requirements. Here 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"
   />

回答1:


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 so you don't have problems when you're dealing with a recycled row. Then in your activity:

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



回答2:


use android:textColor="hex code" parameter inside the TextView tag




回答3:


You can change through xml and java code(runtime) also....

in xml widget you need to define ::

 android:textColor="Hex code"

Like ::

android:textColor="#000000"

at runtime you need to define ::

 TextView tv = (TextView) aView.findViewById(R.id.txvx);
                tv.setTextColor(Color.RED);


来源:https://stackoverflow.com/questions/9460407/change-text-color-for-listview-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!