Selected list item color moves on scrolling the listView in Android

烂漫一生 提交于 2019-12-12 13:33:59

问题


In my Android application I am using listview. The code for list view is as follows

 <ListView
    android:id="@+id/inputselect_listview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:choiceMode="singleChoice"
    android:footerDividersEnabled="true"
    android:headerDividersEnabled="true"
    android:listSelector="@drawable/list_selector"
    android:splitMotionEvents="true" >
 </ListView>

When user selected one item from the listview then background color of list item changes according to this line

android:listSelector="@drawable/list_selector"

EDIT: list_selector.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_window_focused="false" android:state_selected="true"
    android:drawable="@android:color/transparent" />
<item android:state_selected="true"
    android:drawable="@android:color/transparent" />
<item android:state_pressed="true" android:state_selected="false"
    android:drawable="@android:color/transparent" />
<item android:state_selected="false"
    android:drawable="@color/blue_train" />
</selector>

list_selector.xml is in drawable folder to specify color. Now the problem is that when I select one item from listview and scrolls the list then selected item background color also move downward/upward according to scrolling. Please provide me solution so that selected item background color remains as it is on scrolling.

EDIT:Here the screenshot of scrolling listview by selecting single item.Blue color remains as it is

Please advice.


回答1:


seems uncleared states in selector causing this . use one like

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 

  <!-- Selected --> 
  <item 
    android:state_focused="true" 
    android:state_selected="false" 
    android:drawable="@drawable/focused"/> 

  <!-- Pressed -->
  <item 
    android:state_selected="true" 
    android:state_focused="false"
    android:drawable="@drawable/pressed" /> 

<!-- default -->
  <item  android:drawable="@drawable/default" /> 

</selector> 



回答2:


add line in getView() method; convertView.setBackgroundResource(selectedItemInAactivityList.contains.(arrayListSetInAdaptor.get(position) ? r.drawable.selected : R.drawable.transperant));

This one line solved your problem




回答3:


Store clicked/selected positions in a set or array in your onItemClick() method. Write code to handle color in getview() method of your adapter using stored positions.



来源:https://stackoverflow.com/questions/15472229/selected-list-item-color-moves-on-scrolling-the-listview-in-android

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