【发布时间】:2020-11-17 00:56:58
【问题描述】:
我正在关注这个问题
how to store recyclerview data on onSaveInstanceState
我还发现 How to save state of view class? 和 Fragment save view state。
上下文
我在我的一个片段中以 DataModel(实现 Parcelable) 的形式将数据提供给 recyclerview。
使用底部导航和ROOM DB(获取和保存数据)。
我已经做了什么
我在第一个链接和我的代码中使用了代码。但是我无法理解其中使用的第四个代码和平(我没有response.boddy(),错误)。
无论如何每次都更改视图savedInstanceState = null,所以代码正在重做。
我想要什么或问题
我不想每次通过底部导航更改视图时都重做工作?
我做错了什么,数据没有保存在savedInstanceState?
我的片段视图
private ArrayList<DataModel> data;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_home, container, false);
currentContext = getContext();
recyclerView = (RecyclerView) root.findViewById(R.id.recyclerViewHome);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
this.data = new ArrayList<>();
adapter = new CustomAdapter(data, currentContext, 1);
recyclerView.setAdapter(adapter);
if (savedInstanceState != null) {
// Retrieve the data you saved
data = savedInstanceState.getParcelableArrayList("saved_data");
//Call method to reload adapter record
recyclerViewsaveInstance(data);
}
else {
//No data to retrieve
dataAsynTask; //deleted, Basicly I get the data from DB, convert it to DataModel and give them to recyclerview.
}
return root;
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.i("savedInstanceState", "loading");
savedInstanceState.putParcelableArrayList("saved_data", this.data);
super.onSaveInstanceState(savedInstanceState);
}
public void recyclerViewsaveInstance(ArrayList<DataModel> dataset)
{
this.data = dataset;
adapter = new CustomAdapter(dataset, getContext(), 1);
recyclerView.setAdapter(adapter);//notify adapter about the new record
adapter.notifyDataSetChanged();
}
【问题讨论】:
-
听起来你在说
savedInstanceState捆绑包每次都是null;这可能意味着您的Activity中存在问题(或者您创建FragmentTransaction以显示您的Fragment的任何地方)。您可以将该代码添加到您的问题中吗? -
另外,也许对保存实例状态的概念存在误解。
onSaveInstanceState()在片段被销毁并通过配置更改重新创建时调用(例如当您旋转手机时)。如果您使用底部导航切换到不同的视图然后切换回来,则不会使用onSaveInstanceState()。如果您希望在执行此操作时缓存您的 recyclerview 数据,则必须将其保存在其他地方(可能在托管底部导航和片段的Activity中)。 -
我想我正在做你所说的(在视图之间切换)。你的意思是要以某种方式保存hole recyclerview吗?
-
我添加了我在 MainActivity 中的内容。
标签: android android-fragments android-recyclerview savestate onsaveinstancestate