我创建了一个位于较大 Activity 内的 ListView ( ListView 占据了屏幕的一半,上面有输入/按钮)。此 ListView 使用自定义适配器绘制行 View 。
行 View 内有一个按钮,单击/点击时我希望 Activity 处理该按钮,而不是适配器。但是我不知道如何在适配器类内部告诉它使用该 Activity 。由于它是面向对象的,我假设我必须在设置适配器时传递某种对 Activity 的引用(而不是将父 Activity 硬编码到适配器中)。
我在 Activity 和适配器之间共享数据集时遇到了一个更简单的问题(我希望适配器使用 Activity 中的数组列表),但是我也无法解决这个问题,所以我最终将数组列表作为复制到适配器中。所以我希望解决点击监听器,也意味着我可以摆脱必须创建的重复数据?
所有代码都非常简单,但这里有一个粗略的轮廓:
设置列表适配器并声明数据集(这是 Activity 数据集,而不是适配器)
numbersListAdapter = new NumberListAdapter(this);
numbersList.setAdapter(numbersListAdapter);
this.selectedContacts = new HashMap<Long, HashMap<String, String>>();
将条目添加到 Activity 数据集中并添加到适配器数据集中
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 编程。所以我已经知道代码很可能效率低下而且非常糟糕。但我必须以某种方式学习 :)
编辑
好吧,我意识到我有点傻,我只需要使用传递给适配器的上下文来引用父 Activity 。但是我还是不明白。继承人的代码:
适配器的构造函数
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 收到两条消息,第一条发生在我注释掉监听器时,我得到
未使用字段 NumberListAdapter.parentActivity 的值
一旦我添加了监听器
View 类型中的方法 setOnClickListener(View.OnClickListener) 不适用于参数 (Context)
显然我做错了什么。可能又犯了一个很愚蠢的错误
最佳答案
如果您需要在单击 ListView 的行时获得回调,您可以使用
但是如果你需要在每一行中点击一个按钮,你将不得不覆盖
adapter 的getView 函数,然后分别设置按钮的onclicklistener
编辑: 将上下文类型转换为 Activity
theBtn.setOnClickListener((YourActivity)this.parentActivity);
关于android - Listview 自定义适配器通知父 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12011095/