I am having problems defining a ListView with a custom adapter and list item xml layout. The problem is that my ListView is not highlight items when pressed. I am doing the following:
I define a drawable selector xml resource file:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" android:drawable="@android:color/holo_orange_light" />
<item android:state_pressed="false" android:drawable="@android:color/white" />
</selector>
I define an item layout xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="@drawable/btn_voice_item"
>
<ImageButton
android:id="@+id/voiceItemFavorite"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_centerVertical="true"
android:layout_margin="5dp"
android:background="@drawable/btn_favorite" />
<TextView
android:id="@+id/voiceItemText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_margin="5dp"
android:layout_toRightOf="@+id/voiceItemFavorite"
android:background="@drawable/btn_voice_item" />
</RelativeLayout>
Finally I wrote code in my custom data adapter to inflate and populate then view.
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = context.getLayoutInflater();
convertView = inflater.inflate(R.layout.voice_item, null);
}
VoiceItem i = getItem(position);
TextView t = (TextView) convertView.findViewById(R.id.voiceItemText);
t.setText(i.toString());
ImageButton b = (ImageButton) convertView.findViewById(R.id.voiceItemFavorite);
b.setTag(i);
b.setSelected(i.favorite);
b.setOnClickListener(new FavoriteClick());
return convertView;
}
Everything works except when I press items in the list there is no visual indication of the press. I expect the color of the pressed item’s background to transition to the style defined by my drawable selector.
How can I both have a custom view items and retain styling highlighting of items while pressed?
If
android:background="@drawable/btn_voice_item"is solid image so it’ll cover theListViewselector. Here is very detail tutorial about customListView selectorand item backroundListViewTipsandTricks part3 (Cyril Mottier)