androidlistviewmultichoiceitems

Android ListView Multi-Choice don't show highlight after chlicking


I have a ListView in the multi-choice mode. I don't want check box. I just want when i click on items, they could highlight to show checked state. when clicking again, the highlight will disappeared and unchecked.

So now my problem is my items are not checked and highlight at all. I don't know why.

Here is the code:

mFriendList.setAdapter(adapter);
        mFriendList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        mFriendList.setOnItemClickListener(new FriendsItemClickListener());
        }
}


// The click listener for FriendsList
private class FriendsItemClickListener implements
        ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        Log.d("ItemClickPosition", String.valueOf(position));

        // if already checked, then uncheck
        if(mFriendList.isItemChecked(position)){
            mFriendList.setItemChecked(position, false);
            Log.d("OnItemClick", String.valueOf(mFriendList.isItemChecked(position)));
        }else{
            // if uncheck, then check
            mFriendList.setItemChecked(position, true);
            Log.d("OnItemClick", String.valueOf(mFriendList.isItemChecked(position)));
        }
    }

now the problem is the items are never checked or show highlight. and all the log I got is:

ItemClickPosition   0 
OnItemClick         false
ItemClickPosition   1 
OnItemClick         false
ItemClickPosition   2 
OnItemClick         false

why they are not selected?


Solution

  • Use selector like below

    highlight.xml

    <selector xmlns:android="http://schemas.android.com/apk/res/android" >
        <item 
            android:state_activated="true"
            android:drawable="@color/pressed_color"/>
    
    </selector>
    

    & Use this in your relative/linear layout like below

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
    
        android:layout_height="match_parent"
    
    
        android:background="@drawable/highlight"
    >