我创建了一个位于更大活动中的列表视图(列表视图占据了屏幕的一半,上面有输入/按钮)。此列表视图使用自定义适配器绘制行视图。
行视图中有一个按钮,当单击/点击时,我希望处理该活动,而不是适配器。然而,我不知道在适配器类内部如何,我可以告诉它使用该活动。由于它是OOP,我假设在设置适配器时必须传递某种对活动的引用(而不是将父活动硬编码到适配器中)。
我在活动和适配器之间共享数据集时遇到了一个类似的问题(我希望适配器使用活动中的arraylist),但我也无法解决这个问题,所以我最终将arraylist作为副本传递到适配器中。所以我希望找到点击监听器,这也意味着我可以摆脱必须创建的重复数据?
所有的代码都很简单,但这里有一个粗略的概述:
设置列表适配器&声明数据集(这是活动数据集,而不是适配器)
numbersListAdapter = new NumberListAdapter(this);
numbersList.setAdapter(numbersListAdapter);
this.selectedContacts = new HashMap<Long, HashMap<String, String>>();
将条目添加到活动数据集并添加到适配器数据集
HashMap<String, String> tempa = new HashMap<String,String>();
tempa.put("name", name);
tempa.put("number", number);
this.selectedContacts.put(contactID, tempa);
this.numbersListAdapter.addEntry(contactID, tempa);
适配器添加条目
public void addEntry(Long id, HashMap<String, String> entry) {
entry.put("contactID", id.toString());
this.selectedNumbers.add(entry);
this.notifyDataSetChanged();
}
适配器构造函数
public NumberListAdapter(Context context) {
selectedNumbers = new ArrayList<HashMap<String, String>>();
mInflater = LayoutInflater.from(context);
}
请注意:这是我第一次尝试这种东西。我从来没有做过android、java和非常非常少的OO编程。所以我已经知道代码很可能效率低下,而且非常糟糕。但我必须以某种方式学习:)
编辑
好吧,所以我意识到我有点傻,我只需要使用传递到适配器中的上下文来引用父活动。但是我还是不明白。这是代码:
适配器的构造函数
numbersListAdapter = new NumberListAdapter(this);
变量声明和构造函数方法
public class NumberListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<HashMap<String, String>> selectedNumbers;
private Context parentActivity;
public NumberListAdapter(Context context) {
parentActivity = (Context) context;
selectedNumbers = new ArrayList<HashMap<String, String>>();
mInflater = LayoutInflater.from(context);
}
监听器
Button theBtn = (Button)rowView.findViewById(R.id.actionRowBtn);
theBtn.setOnClickListener(this.parentActivity);
我从eclipse收到了两条消息,第一条发生在我对听众发表评论时,我得到The value of the field NumberListAdapter.parentActivity is not used
一旦我在中添加侦听器,我就会得到
The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (Context)
显然我做错了什么。可能又是一个相当愚蠢的错误
如果您需要在列表视图的行被点击时获得回调,您可以使用
numbersListAdapter.setOnitemitemClickLiistener
但是,如果你需要在每一行内点击一个按钮,你就必须覆盖
获取适配器的View函数,然后单独设置按钮的onclicklistener
编辑:键入上下文到活动
theBtn.setOnClickListener((YourActivity)this.parentActivity);