我试图从MainActivity中调用片段中的适配器上的notifyDataSetChanged()
,以便在更改数据后刷新视图/列表。我在OnActivityCreate()
内创建了适配器,因此我无法找到如何获取适配器,因此我可以创建一个调用方法adapter.notifyDataSetChanged()
片段
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] names = new String[] { "name1", "name1", "name1" };
String[] values = new String[] { "value1", "value2", "value3" };
MyArrayAdapter adapter = new MyArrayAdapter(getActivity(), names, values);
setListAdapter(adapter);
}
我尝试在Fragment中创建一个方法并将adapter
传递给它,但我无法从主活动中调用它。另外getListAdapter()
也不允许我致电notifyDataSetChanged()
。这里很困惑,谢谢!
答案 0 :(得分:1)
让它对整个活动都可见。
... MyClass {
private MyArrayAdapter adapter;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] names = new String[] { "name1", "name1", "name1" };
String[] values = new String[] { "value1", "value2", "value3" };
adapter = new MyArrayAdapter(getActivity(), names, values);
setListAdapter(adapter);
}
// Another method
private void myMethod() {
adapter.notifyDataSetChanged();
}
}