我有一个 ListView,我想更改列表中所选项目的颜色。我可以更改下方所选项目的颜色,但如何将所有其他项目的颜色恢复(或更改)为原始颜色?
@Override
public void onListItemClick(ListView parent, View v, int position, long id)
v.setBackgroundColor(Color.CYAN);
}
我尝试更改父项的颜色,但它不会更改项目的颜色:
@Override
public void onListItemClick(ListView parent, View v, int position, long id)
parent.setBackgroundColor(Color.WHITE);
v.setBackgroundColor(Color.CYAN);
}
ListView :
<ListView
android:id="@id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
android:clickable="true"
android:focusable="false"
android:focusableInTouchMode="false"
android:drawSelectorOnTop="false" />
每个项目是:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/contacts_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout android:id="@+id/linear"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text=""/>
<TextView
android:id="@+id/lastname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:layout_marginLeft="3sp"
android:text=""/>
<TextView
android:id="@+id/firstname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:layout_marginLeft="3sp"
android:text=""/>
<TextView
android:id="@+id/sipExt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="15sp"
android:textColor="#59696E"
android:gravity="right"
android:layout_marginRight="9dp"
android:textStyle="italic"
android:text=""/>
</LinearLayout>
<TextView
android:id="@+id/alias"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:textColor="#a69d86"
android:textStyle="italic"
android:layout_below="@id/linear"
android:text=""/>
最佳答案
执行此操作的正确方法是定义自定义 Selector
并设置颜色 (Drawable) 并根据您希望它们在每个状态中的颜色设置颜色。有关详细信息,请参阅此链接:
Can't add custom selector to ListView
这里:
Android ListView selected item stay highlighted
-- SO 上也有很多关于此的其他帖子。
如果你想保留你当前的设计,你可以尝试这样的事情:
View lastTouchedView;
@Override
public void onListItemClick(ListView parent, View v, int position, long id)
lastTouchedView.setBackgroundColor(Color.WHITE);
v.setBackgroundColor(Color.CYAN);
lastTouchedView = v;
}
关于android - 更改 ListView 中项目的颜色 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17838036/