我有一个类MyArrayAdapter,它扩展了ArrayAdapter<MyClass>。现在我有了一个MyListFragment,它扩展了ListFragment,它使用MyArrayAdapter。类MyActivity在视图中添加MyListFragment。
到目前一切尚好。
现在,用户可以更改首选项,在此基础上,我需要更改List<MyClass>中的一些字符串。由于ArrayAdapter只在onNotifyDataSetChanged()上使用自己的方法(如clear(), add(), etc )时才会识别List<MyClass>,所以我使用onResume重新加载数据以反映更改。
因此,我的MyListFragment包含以下内容:
public class MyListFragment extends ListFragment {
private List<MyClass> elements = null;
private MyListAdapter myListAdapter = null;
public MyListFragment(List<MyClass> elements) {
this.elements = elements;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myListAdapter = new MyListAdapter(inflater.getContext(), R.layout.foo, elements);
setListAdapter(myListAdapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onResume() {
myListAdapter.clear();
myListAdapter.addAll( sqliteclass.getAllElements() );
myListAdapter.notifyDataSetChanged();
isSecondTime = true;
super.onResume();
}
}这是可行的,但问题是,当活动第一次运行,现在有2行程到数据库的一个是必要的。因此,我修改了这个类如下:
public class MyListFragment extends ListFragment {
private List<MyClass> elements = null;
private MyListAdapter myListAdapter = null;
private boolean isSecondTime = false; //NEW
public MyListFragment(List<MyClass> elements) {
this.elements = elements;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myListAdapter = new MyListAdapter(inflater.getContext(), R.layout.foo, elements);
setListAdapter(myListAdapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onResume() {
if(isSecondTime){ //NEW
myListAdapter.clear();
myListAdapter.addAll( sqliteclass.getAllElements() );
} //NEW
myListAdapter.notifyDataSetChanged();
isSecondTime = true;
super.onResume();
}
}因此,我的问题是,我通过使用boolean 来确保第一次不对DB进行2次访问是可靠的吗?适配器保存元素列表,因此第二次只进行一次旅行。
(例如。如果用户更改了首选项,切换到其他应用程序,而Android决定释放一些内存,并将MyListFragment从内存中移除,当用户切换回来时,是否可以确保List<Elements>将从db中更新?-这或任何类似的场景)
如有任何建议,敬请见谅。
发布于 2014-02-24 07:39:32
我认为您应该将Adapter存储在Activity中,开始时只填充一次,并且独立于Fragment's生命周期。为它做一个getter,并通过Fragment通过(MyActivity) getActivity().getMyAdapter()访问它。
关于你的第二个问题:如果用户切换到另一个应用程序,有三种可能的场景:
在任何情况下你都是安全的。
发布于 2014-02-23 10:35:52
我总是在onResume()中这样做
public void setList() {
Log.i("setList","");
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice);
if (items.size()<1)
adapter.add(getString(R.string.emptylist));
for(int i=0;i<items.size();i++) {
adapter.add(items.get(i).item);
}
todolist.setAdapter(adapter);
for(int i=0;i<items.size();i++) {
todolist.setItemChecked(i, items.get(i).checked);
}
}每次需要更新列表时,我都会添加一个新适配器。
https://stackoverflow.com/questions/21967030
复制相似问题