Android 将参数传递给列表视图行中按钮上的 onclick 侦听器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3471613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing a parameter to onclick listener on a button in a listview row
提问by Richard
I just started android and I'm running into some problems.
I have created a ListView
that is populated from a database.
Each row has a button to delete the item from the list and the database.
我刚开始使用 android,但遇到了一些问题。
我创建了一个ListView
从数据库填充的。
每行都有一个按钮,用于从列表和数据库中删除项目。
I am able to hook up an event listener to the button but I have not been able to determine the matching database record to be deleted.
我能够将事件侦听器连接到按钮,但我无法确定要删除的匹配数据库记录。
My class is shown below
我的班级如下所示
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: ");
}
So how can I pass the database record ID to the handler so I can use the database adapter to delete it?
那么如何将数据库记录 ID 传递给处理程序,以便我可以使用数据库适配器删除它呢?
回答by Pentium10
You should store the ID of the record in the Tag, call setTag()
on your view, and to read in onclick call getTag()
您应该将记录的 ID 存储在标签中,调用setTag()
您的视图,并读取 onclick 调用getTag()
回答by RoflcoptrException
Create a inner class that implements OnClickListener and then pass the position variable in the constructor.
创建一个实现 OnClickListener 的内部类,然后在构造函数中传递位置变量。
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;
}
}