Get position in ListView

I use ListView to display multiple items. My row.xml as below:

<TextView android:text="text" android:id="@+id/tvViewRow" android:layout_width="wrap_content" android:layout_height="wrap_content"> </TextView> <Button android:text="Click me!" android:id="@+id/BtnToClick" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="myClick"> </Button> 

And I define myClick in action, as shown below:

 public void myClick (View v) { LinearLayout vwParentRow = (LinearLayout)v.getParent(); //How to get the position } 

How to find out the position that you need to click on the button? Position means the same as the onListItemClick method.

 @Override protected void onListItemClick(ListView l, View v, int position, long id) { } 
+8
android listview
source share
5 answers

Try

 public void DetailClick(View v) { ListView lv = getListView(); int position = lv.getPositionForView(v); } 
+35
source share

You can try this.

Step 1. In your user adapter

 @Override public view getView(int position, View convertView, ViewGroup parent){ .......//Perform your logic convertView.findViewById(R.id.BtnToClick).setTag(position); return convertView; } 

Step 2: In listening onclick

  public void myClick (View v) { LinearLayout vwParentRow = (LinearLayout)v.getParent(); position=(Integer) v.getTag(); } 
+5
source share

Yes, the position in onListItemClick is the same as the position of the item clicked in the list.

+1
source share

If I understand your question correctly, you have a button in each row of the ListView , and you want to know which row received the button click. How do you do setOnClickListener() on a button? The reason I ask this is if you set the OnClickListener for each button, you already know the position of that button.

+1
source share

You should also read the documentation for ListView and even look at the available methods and their code examples.

Know your documentation.

+1
source share

All Articles