Get position in ListView

2020-07-07 03:04发布

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) {
}

5条回答
贼婆χ
2楼-- · 2020-07-07 03:28

Try

public void DetailClick(View v) {
ListView lv = getListView();
int position = lv.getPositionForView(v);
}
查看更多
神经病院院长
3楼-- · 2020-07-07 03:28

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();
  }
查看更多
forever°为你锁心
4楼-- · 2020-07-07 03:29

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.

查看更多
Anthone
5楼-- · 2020-07-07 03:42

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

Know your documentation.

查看更多
Juvenile、少年°
6楼-- · 2020-07-07 03:46

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

查看更多
登录 后发表回答