Reputation: 712
I am facing a problem with android listview. I have multiple Buttons inside my ListView and I want to setclicklistener for each Buttons and retrieve their position in 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));
button OnClickListener
btnList.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
new DrawerItemClickListener();
}
});
class 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);
}
}
Upvotes: 0
Views: 1039
Reputation: 390
You need to handle the on click listener of the button inside the getview of the listview adapter, where you find the button using view.findViewById(R.id.yourButtonID). This is how you can do it :
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()
}
});
Upvotes: 0
Reputation: 1065
Use this and the position in OnItemClick is the button's position in the list
listview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
}
Upvotes: 1