我创建了一个位于较大活动内的列表视图(列表视图占据了屏幕的一半,上面有输入/按钮)。此列表视图使用自定义适配器来绘制行视图。
行视图内部是一个按钮,当单击/点击它时,我希望活动处理,而不是适配器。但是我不知道如何在适配器类内部,我可以告诉它使用活动。由于它是 OOP,我假设我必须在设置适配器时传递对活动的某种引用(而不是将父活动硬编码到适配器中)。
我在活动和适配器之间共享数据集时遇到了一个更简单的问题(我希望适配器使用活动中的数组列表),但是我也无法解决这个问题,所以我最终将数组列表作为副本传递到适配器。所以我希望解决点击监听器,也意味着我可以摆脱必须创建的重复数据?
所有代码都非常简单,但这里有一个粗略的大纲:
设置列表适配器和声明数据集(这是活动数据集,而不是适配器)
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)
显然我做错了什么。可能又是一个非常愚蠢的错误