开发者

onItemClick listener problem in ListView

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>


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜