Wednesday, December 19, 2012

Android: ListView custom layout with ImageButton of android:focusable="false"

Here I have customized the layout of a ListView. A ListItem is constructed by a TextView and a ImageButton. By default the ImageButton is invisible. I have OnItemLongClickListener implemented in the activity and make the button visible on onItemLongClick. Under the normal scenario everything works fine until you set the visibility to visible of the ImageButton. When you set the visibility to visible you won't be able to click on that particular ListItem anymore. 

This particular behavior is caused by the ImageButton. Reason for this is one particular property of the ImageButton which is android:focusable. By default this is true and you have to set this to false. But the tricky part is it doesn't work when you set the property in the xml layout as android:focusable="false". The Reason behind this is android:focusable gets overwritten and set to true by the ImageButton's constructor. So if you want to set android:focusable="false", do it in the java file instead of doing it in the xml layout file and you have to set android:focusable="false" in these kinds of situations otherwise you'll face the above mentioned (mis)behavior.