我创建了一个列表视图,位于较大的活动(列表视图填充屏幕的一半,其上方有输入/按钮)。此列表视图使用自定义适配器来绘制行视图。Listview自定义适配器通知父活动
行视图内部是一个按钮,当点击/点击我想要处理活动,而不是适配器。但是我不知道如何在适配器类中,我可以告诉它使用该活动。由于它是OOP,我假设我必须在设置适配器时(而不是将父活动硬编码到适配器中)传递某种活动的引用。
我在活动和适配器之间共享一个数据集(我希望适配器使用活动中的数组列表)有一个类似问题,但是我无法解决这个问题,所以我最终将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);
0123构造
我从日食两个消息中,第一次出现时,我注释掉的听众,我也得到 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)
显然,即时通讯做错了什么。也许相当愚蠢的错误再次太
感谢您的答复,但我已经做了所有这一切,我有一个自定义列表视图行了,我知道如何设置监听器。我的问题是我想要点击侦听器是列表(和列表适配器)在里面的活动,我不知道如何从适配器引用父活动。但是,感谢您的回复 – Lee 2012-08-18 12:09:10
保存您的适配器内的上下文不起作用? – nandeesh 2012-08-18 12:10:45
我真的只是想到了这一点。我只想到,我将“this”传递给活动中的构造函数,显然,传递的上下文就是活动。我现在就试试它(应该可以)。不能相信我有多愚蠢,我一直没有意识到这一点(就像我第一次在Java/Android中第一次尝试坚持OOP结构一样)。但是,谢谢你所有相同 – Lee 2012-08-18 12:17:07