如何在列表视图中获取 child 的位置?

How get position of child inside listview?

在下面的代码中,如何获取点击按钮的 Button 位置?

public class HistoryAdapter extends CursorAdapter {
Button button;
TextView text;

public HistoryAdapter(Context context, Cursor c, int flags) {
    super(context, c, flags);
}

@Override
public View newView(final Context context, Cursor cursor, ViewGroup parent) {
    View view = LayoutInflater.from(context).inflate(R.layout.historylist, parent, false);
    return view;
}

@Override
public void bindView(View view, final Context context, final Cursor cursor) {
    text = (TextView) view.findViewById(R.id.text);
    button = (Button) view.findViewById(R.id.btn);
    String body = cursor.getString(cursor.getColumnIndex("name"));
    text.setText(body);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

}

}

如果您需要项目在列表中的位置,您可以从传递给 onClick 方法的视图中访问它,参考 this link 您可以编辑代码:

@Override
public void bindView(View view, final Context context, final Cursor cursor) {
    text = (TextView) view.findViewById(R.id.text);
    button = (Button) view.findViewById(R.id.btn);
    String body = cursor.getString(cursor.getColumnIndex("name"));
    text.setText(body);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position=(Integer)v.getTag();
        }
    });
}

希望它有用:)

以下代码应该有效(final 很重要):

    @Override
public void bindView(View view, final Context context, final Cursor cursor) {
    text = (TextView) view.findViewById(R.id.text);
    button = (Button) view.findViewById(R.id.btn);
    String body = cursor.getString(cursor.getColumnIndex("name"));
    final int position = cursor.getPosition();
    text.setText(body);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            doSomething(position);
        }
    });