Home » Android » android – Get position in ListView

android – Get position in ListView

Posted by: admin June 15, 2020 Leave a comment

Questions:

I use ListView to show several 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 Activity as below:

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

How to know the position which buttom be clicked?
The position mean same as the method onListItemClick’s.

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
}
How to&Answers:

Try

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

Answer:

You can try like this.

Step 1: In your custom 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 onclick listener

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

Answer:

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

Answer:

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

Answer:

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

Know your documentation.