我遇到了android listview的问题。我的 ListView 中有多个按钮,我想为每个按钮设置setclicklistener并检索它们在ListView中的位置。
ListItem.xml
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/btnList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:textColor="#fff" />
MainActivity.java
mDrawerList.setAdapter(new ArrayAdapter<String>(
getApplicationContext(), R.layout.drawer_list_item,
mPlanetTitles));
按钮OnClickListener
btnList.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
new DrawerItemClickListener();
}
});
班级DrawerItemClickListener
private static class DrawerItemClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
MainActivity main= new MainActivity();
main.selectItem(position);
}
}
答案 0 :(得分:1)
使用此选项,OnItemClick中的位置是按钮在列表中的位置
listview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
}
答案 1 :(得分:0)
您需要在listview适配器的getview中处理按钮的on click侦听器,您可以使用view.findViewById(R.id.yourButtonID)找到该按钮。 这就是你如何做到的:
Button yourButton= (Button) rowView.findViewById(R.id.yourButtonID); // be carefull to use the view of the listItem and not the activity in case the adapter is inside the Activity.
yourButton.setTag(position);// Any data associated with the button has to be added with setTag()
yourButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Log.w("DEBUG_TAG", "Button Clicked at position : " + position);
//here you must use getTag() in order to extract the data set in the setTag()
}
});