android - 设置 ListView 项的颜色

标签 android

我正在尝试将某些 ListView 项目(如电话号码和电子邮件地址)的颜色单独设置为蓝色,以便用户知道它们是可点击的。这是一个 fragment ,但实现它根本不起作用,当您滚动列表时,列表项会随机改变颜色。

    List<Map<String, String>> data = new ArrayList<Map<String, String>>();

    //...add data to list

    SimpleAdapter adapter=new SimpleAdapter(this, data, R.layout.simple_list_item_2_custom, new String[] { LABEL, VALUE },
        new int[] { R.id.text1, R.id.text2 })
    {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) 
        {
            LinearLayout view = (LinearLayout)super.getView(position, convertView, parent);

            String label = data.get(position).get(LABEL);

            if (label.equals("Email Address"))
            {
                ((TextView)view.getChildAt(0)).setTextColor(Color.BLUE);
            }

            return view;
        }
    };

下面是定义列表项的 LinearLayout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?android:attr/listPreferredItemHeight"
    android:orientation="vertical" >
    <TextView android:id="@+id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="?android:attr/listPreferredItemPaddingStart"
        android:layout_marginTop="8dip"
        android:textAppearance="?android:attr/textAppearanceSmall" />
    <TextView android:id="@+id/text2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignStart="@android:id/text1"
        android:textAppearance="?android:attr/textAppearanceListItem" />
</LinearLayout>

最佳答案

你错过了 "if (label.equals("Email Address"))"的 else

当它不是电子邮件地址时,您必须放置另一种文本颜色,如下所示: ((TextView)view.getChildAt(0)).setTextColor(Color.WHITE);

原因是 Android 适配器重用了不再显示的旧行,在本例中是您已经定义为蓝色的行。

关于android - 设置 ListView 项的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17456673/

相关文章:

android - sed问题:“错误模式”

android - RecyclerView 列表中的最后一项位置错误

java - 使用模型类 Android 从 Firebase 访问用户信息

android - 有试用效果的Andengine

android - target-densitydpi和window.innerWidth与Android H5有什么关系

android - 按下启动另一个 Activity 的按钮时应用程序崩溃

android - ListView 监听器不工作

Android:在 MaterialTheme 中使用自定义样式的 AlertDialog 抛出资源未找到异常

android - 与 Apportable 交叉编译相机应用程序

java - Linux - Android Studio 1.1 Beta 3 - 未找到默认 Activity