1

My goal is to make a ListView of each row of which contains one single button which occupies the entire space in each row. Below is the code where the onItemClick method does not work.Does anyone have idea why it does not work?

I have next class Activity:

public class MyActivity extends Activity implements OnItemClickListener {

public void onCreate(Bundle savedInstanceState) {

//
//Here is a lot of code..
//.....

List<String> items = new ArrayList<String>();
ListView lv = (ListView) findViewById(R.id.listView);

if (result.getItems().size() > 0) {
// Init list view
lv.setVisibility(lv.VISIBLE);
lv.setTextFilterEnabled(true);
lv.setAdapter(new buttonAdapter(this, R.layout.list_item,
                    items));
lv.setOnItemClickListener(this);
}
}
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {

//....
}
}

And here is my XML-element for each row in the ListView:

<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/list_item_button"
android:layout_gravity="center_vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textStyle="bold"
android:textSize="16sp">
</Button>
Speise
  • 789
  • 1
  • 12
  • 28

2 Answers2

3

onItemClick only fires when the item itself is clicked. If you had a TextView or a TextView and an ImageView instead of a Button, clicking the item then will trigger onItemClick.

If you want to respond to a button click, you can set up an onClickListener for each button in the adapter. Then use the view references passed to the listener to distinguish between items.

However, if you do want the onItemClick to be triggered, you will need to add the property

 android:descendantFocusability="beforeDescendants" 

to the ListView tag in the layout XML.
This lets the ListView handle the click first.

As to why you want a button that fills an entire listitem instead of letting the listitem be clickable itself, that still doesn't quite make sense. You should do one or the other, since whatever you do, only one of them will actually be clicked.

CodeFusionMobile
  • 14,812
  • 25
  • 102
  • 140
  • Also check out this similar question that deals with putting focusable elements in a listview in more detail. http://stackoverflow.com/questions/2679948/focusable-edittext-inside-listview – CodeFusionMobile Aug 11 '11 at 13:51
  • As a result I solved this just using onClickListener for each button. Thank You a lot! – Speise Aug 12 '11 at 08:21
0

If the button you want to place on the listview item occupies the whole item width and height the onItemClickListener will not be envoked since there is no content space to click/touch. You can implement the onClickListener() (or onTouchListener()) for the button. But why button, you can do the same without button but just with click on the listview item as it is.

Nikola Despotoski
  • 49,966
  • 15
  • 119
  • 148