I am using this code, but it just does nothing:
Added to my listview:
android:listSelector="@drawable/list_selector"
Then xml files in drawable to control the diferent states
@drawable/list_selector
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/list_item_bg_normal" android:state_activated="false"/>
<item android:drawable="@drawable/list_item_bg_pressed" android:state_pressed="true"/>
<item android:drawable="@drawable/list_item_bg_pressed" android:state_activated="true"/>
</selector>
@drawable/list_item_bg_normal
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#ff0000"
android:endColor="#ffffff"
android:angle="90" />
</shape>
@drawable/list_item_bg_pressed
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#ff0000"
android:endColor="#ffffff"
android:angle="90" />
</shape>
In the Activity:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setSelected(true);
Add
adapter.notifydatasetchanged();
Your Code Looks like this
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setSelected(true);
adapter.notifydatasetchanged();
Please update your selector file like below and call notify data set changed. And inside the adapter, you need to maintain a flag to maintain selection when the list is scrolled.
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/list_item_bg_pressed" android:state_pressed="true"/>
<item android:drawable="@drawable/list_item_bg_pressed" android:state_selected="true"/>
<item android:drawable="@drawable/list_item_bg_normal"/>
</selector>
Then
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setSelected(true);
list.get(position).isSelected=true; // list is array items passed to adapter
adapter.notifydatasetchanged();
)
}
In getView method of your adapter maintain selection by using a boolean like
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(list.get(position).isSelected){
convertview.setSelected(true)
}else{
convertview.setSelected(false)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.