Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't click on ListView row with imagebutton

I have trouble with a ListView. Its items (rows) have an ImageButton. The ImageButton has android:onClick set, so this onClick event is working, but click on row doesn't work.

If I remove the ImageButton from the row item, click on row works (ListView has correct onClick listener). How can I fix it? I need onClick event when the user clicks on the ImageButton, and the standard click event when the user selects the row (not click the ImageButton but click the row).

My ListView:

<ListView xmlns:android="http://schemas.android.com/apk/res/android"         android:id="@+id/restaurants_list"         android:layout_width="fill_parent"         android:layout_height="fill_parent"         android:divider="@color/list_devider"         android:dividerHeight="1dp"         android:cacheColorHint="@color/list_background" />  
like image 858
yital9 Avatar asked Jul 11 '12 08:07

yital9


2 Answers

Unfortunately,

android:focusable="false" android:focusableInTouchMode="false" 

doesn't work for ImageButton.

I finally found the solution here. In your layout xml for those items, add

android:descendantFocusability="blocksDescendants"  

to the root view.

It works perfectly for a ListView that has ImageButtons. According to official reference, blocksDescendants means that the ViewGroup will block its descendants from receiving focus.

like image 118
leoly Avatar answered Sep 17 '22 18:09

leoly


You can use a custom adapter for your listView (if you haven't already). And there, in the getView(int position, View inView, ViewGroup parent) method of the adapter do something like this:

@Override public View getView(int position, View inView, ViewGroup parent) {      View v = inView;     ViewHolder viewHolder; //Use a viewholder for sufficent use of the listview      if (v == null) {         LayoutInflater inflater = (LayoutInflater) adaptersContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);         v = inflater.inflate(R.layout.list_item, null);         viewHolder = new ViewHolder();         viewHolder.image = (ImageView) v.findViewById(R.id.ImageView);         v.setTag(viewHolder);     } else {         viewHolder = (ViewHolder) v.getTag();     }          .....      viewHolder.image.setOnClickListener(new OnClickListener() {          @Override         public void onClick(View v) {              //Click on imageView         }i     });      v.setOnClickListener(new OnClickListener() {          @Override         public void onClick(View v) {              //Click on listView row         }     });          .....      return (v); } 

See here if you need help creating your custom adapter.

like image 26
Angelo Avatar answered Sep 17 '22 18:09

Angelo