将参数传递给listview行中按钮上的onclick侦听器

Ric*_*ard 20 android listview button

我刚开始使用android而且遇到了一些问题.
我创建了一个ListView从数据库填充的.
每行都有一个按钮,用于从列表和数据库中删除项目.

我能够将事件监听器连接到按钮,但我无法确定要删除的匹配数据库记录.

我的班级如下所示

public class FeedArrayAdapter extends ArrayAdapter<Feed> implements OnClickListener
{
    private ARssEReaderDBAdapter dba;
    private String TAG = "FeedArrayAdapter";

    public FeedArrayAdapter(Context context, int textViewResourceId, List<Feed> items)          {
    super(context, textViewResourceId, items);
    Log.w(TAG, "List");


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Log.w(TAG, "getView");
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = vi.inflate(R.layout.feedlistrow, null);
    }
    Feed feed = getItem(position);
    if (feed != null) {
        TextView title = (TextView)v.findViewById(R.id.TextView01);
        if (title != null) {
            title.setText(feed.getTitle());
        }
        Button btnDelete = (Button)v.findViewById(R.id.btnDelete);
        btnDelete.setOnClickListener(this); //btnDeleteFeedListener
    }
    return v;
}

public void onClick(View v) {
    Log.w(TAG, "something got clicked: ");
}
Run Code Online (Sandbox Code Playgroud)

那么如何将数据库记录ID传递给处理程序,以便我可以使用数据库适配器将其删除呢?

Pen*_*m10 39

您应该在标签中存储记录的ID,在setTag()视图上调用,以及读取onclick调用getTag()


Rof*_*ion 22

创建一个实现OnClickListener的内部类,然后在构造函数中传递position变量.

 private Class MyClickListener implements OnClickListener {

    private int position;

    public MyClickListener(int position) {
       this.position = position;
    }

    public void onClick(View v) {
       System.out.println("position " + getPosition() + " clicked.");
    }

    public int getPosition() {
      return position;
    }

 }
Run Code Online (Sandbox Code Playgroud)