【问题标题】:Change text color for ListView items更改 ListView 项目的文本颜色
【发布时间】:2013-06-07 12:57:04
【问题描述】:

如何更改添加到ListView 的项目的文本颜色。我需要根据某些条件在代码中以编程方式更改颜色,并将不同的行更改为不同的文本颜色(例如,第 0 行 = 红色,第 1 行 = 白色,第 3 行 = 蓝色等)。在 xml 布局中设置文本颜色不符合我的要求。这是我的代码:

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

还有我的 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"
   />

【问题讨论】:

    标签: android android-listview textview


    【解决方案1】:

    实现您自己的 ArrayAdapter 并覆盖 getView() 方法:

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

    不要忘记提供替代的else 子句将颜色设置为默认值,这样在处理回收行时就不会出现问题。 然后在你的活动中:

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

    【讨论】:

    • 我来到这里是因为我遇到了一个问题,即更改的文本颜色似乎泄漏到另一行,我认为这是您提到的回收行问题。谢谢!
    【解决方案2】:

    在TextView标签内使用android:textColor="hex code"参数

    【讨论】:

      【解决方案3】:

      您也可以通过 xml 和 java 代码(运行时)进行更改....

      您需要在 xml 小部件中定义 ::

       android:textColor="Hex code"
      

      点赞 ::

      android:textColor="#000000"
      

      您需要在运行时定义 ::

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

      【讨论】:

        猜你喜欢
        • 2012-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-25
        • 2018-12-09
        • 2016-09-13
        • 2012-03-10
        • 1970-01-01
        相关资源
        最近更新 更多