在我的活动中,我有两个列表视图,所以我使用两个不同的适配器。我的要求是在列表项中我有一个按钮。单击任何列表视图中的按钮时,列表视图中的数据应该更改。现在的问题是如何在另一个适配器的单击按钮中访问一个适配器的adapter.notifyDataSetChanged()?
答案 0 :(得分:1)
只需在你的onClick方法中
public void onClick(View v)
{
adapter1.notifyDataSetChanged();
adapter2.notifyDataSetChanged();
}
如果您使用listview行中的按钮,那么您应该在getView()方法中执行此操作
@Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View row=convertView;
if(row==null)
{
LayoutInflater inflater=((Activity)context).getLayoutInflater();
row=inflater.inflate(layoutResourceId, parent,false);
holder=new YourHodler();
holder.button=(Button)row.findViewById(R.id.bt);
row.setTag(holder);
}
else
{
holder=(YourHolder)row.getTag();
}
holder.button.setOnClickListner(new View.onClickListener()
{
//update your Any data set which is beign attached to both the adapters
//for example if you are using List<Collection> then you should first
//update it or change it
//then
adapter1.notifyDataSetChanged();
adapter2.notifyDataSetChanged();
}
return row;
}
答案 1 :(得分:0)
实施在您的活动中执行以下操作的方法:
CustomActivity1 extends Activity {
....
//make it public
public void updateLists() {
CustomAdapter1 adapter1 = (CustomAdapter1) ((ListView) findViewById(R.id.list1)).getListAdapter();
CustomAdapter2 adapter2 = (CustomAdapter2) ((ListView) findViewById(R.id.list2)).getListAdapter();
//update the adapters
adapter1.notifyDatasetChanged();
adapter2.notifyDatasetChanged();
}
....
}
为了使自定义适配器起作用,您必须传递Activity
上下文。所以你的两个适配器中的onclick监听器都可以添加如下内容:
CustomAdapter1 { //and in CustomAdapter2
....
private OnClickListener ButtonClick = new OnClickListener() {
public void onClick(View v) {
//...your code
//having the context of the CustomActivity1 stored in a variable from the constructor you can simply do:
customActivity1Context.updateLists();
}
}
....
}