Android使用ViewModel防止屏幕旋转数据丢失教程

由于比较忙,简单记录下个人的ViewModel保存数据使用教程。先看效果图

横竖屏如下:

 

 

假如我现在要保存旋转时候的recyclerview里的所有item数据,我该如何做呢?

不多说,直接上教程

第一步:创建ViewModel对象,继承ViewModel子类AndroidViewModel

package com.example.ai.UI.home;

import android.app.Application;

import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.ai.pojo.ChatMsg;

import java.util.ArrayList;
import java.util.List;

public class HomeViewModel extends AndroidViewModel{

    private static  MutableLiveData<List<ChatMsg>> chatMsgList;

    /**
     * 构造方法而已,照着写就行
     * @param application
     */
    public HomeViewModel(Application application) {
        super(application);
        chatMsgList = new MutableLiveData<List<ChatMsg>>();  
    }

    /**
     * 获取LiveData对象,记得返回的是泛型的对象
     * @return MutableLiveData
     */
    public LiveData<List<ChatMsg>> getChatMsgList() {
        if (chatMsgList == null) {
            chatMsgList = new MutableLiveData<List<ChatMsg>>();
        }
        return chatMsgList;
    }

    /**
     * 把要保存的数据保存到LiveData容器中
     * @param list 传入要保存的数据,假如你要保存的比如说是textview的文本,那你就传入是String...等等
     */
    public void setChatMsgList(List<ChatMsg> list){
        chatMsgList.setValue(list);
    }
}

第二步:在Fragment的onCreateView中创建观察者,并且更新数据。

1.创建Observer对象

 observer= new Observer<List<ChatMsg>>() {
            @Override
            public void onChanged(List<ChatMsg> msgList) {
                chatMsgList = msgList;
                Log.e(TAG,"进入了回调中,msgList数量:"+msgList.size());
                chatAdapter = new ChatAdapter(getActivity(), chatMsgList);
                recyclerView.setLayoutManager(linearLayoutManager);//得到布局管理器
                recyclerView.setAdapter(chatAdapter);
                chatAdapter.notifyItemInserted(chatMsgList.size() - 1);//把msg插入到recyclerview中
                recyclerView.scrollToPosition(chatMsgList.size() - 1);//将RecyclerView定位到最后一行
            }
        };

 2.更新数据,加上这句旋转屏幕的时候会自动进入到匿名observer的回调函数onChanged()中

        homeViewModel.getChatMsgList().observe(getViewLifecycleOwner(),observer);

 整合的代码如下:

public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
...
...
...省略前面的一些初始化代码
//旋转屏幕的时候会进入到回调中

Observer<List<ChatMsg>>  observer= new Observer<List<ChatMsg>>() {
            @Override
            public void onChanged(List<ChatMsg> msgList) {
            //再次更新你的UI,这个onChanged方法内的传参就是你保存的数据
                chatMsgList = msgList;
                Log.e(TAG,"进入了回调中,msgList数量:"+msgList.size());
                chatAdapter = new ChatAdapter(getActivity(), chatMsgList);
                recyclerView.setLayoutManager(linearLayoutManager);//得到布局管理器
                recyclerView.setAdapter(chatAdapter);
                chatAdapter.notifyItemInserted(chatMsgList.size() - 1);//把msg插入到recyclerview中
                recyclerView.scrollToPosition(chatMsgList.size() - 1);//将RecyclerView定位到最后一行
            }
        };
        homeViewModel.getChatMsgList().observe(getViewLifecycleOwner(),observer);

再附上未旋转屏幕时候的一个的生命周期

可以看到没有进入到onChanged函数中,下面是旋转屏幕时候的,截图截不全,干脆附log记录如下:

2023-05-22 20:20:44.141  8425-8425  TAG                     com.example.ai                       E  跑到onPause
2023-05-22 20:20:44.141  8425-8425  HomeFragment TAG:       com.example.ai                       E  onPause:chatMsgs大小:[com.example.ai.pojo.ChatMsg@5cea5a9]
2023-05-22 20:20:44.141  8425-8425  HomeFragment TAG:       com.example.ai                       E  进入了回调中,msgList数量:1
2023-05-22 20:20:44.142  8425-8425  HomeFragment TAG:       com.example.ai                       E  进入了回调中,msgList数量:1
2023-05-22 20:20:44.143  8425-8425  TAG                     com.example.ai                       E  跑到onPause
2023-05-22 20:20:44.143  8425-8425  HomeFragment TAG:       com.example.ai                       E  onPause:chatMsgs大小:[com.example.ai.pojo.ChatMsg@5cea5a9]
2023-05-22 20:20:44.143  8425-8425  HomeFragment TAG:       com.example.ai                       E  进入了回调中,msgList数量:1
2023-05-22 20:20:44.143  8425-8425  HomeFragment TAG:       com.example.ai                       E  进入了回调中,msgList数量:1
2023-05-22 20:20:44.145  8425-8425  TAG                     com.example.ai                       E  跑到onStop
2023-05-22 20:20:44.145  8425-8425  HomeFragment TAG:       com.example.ai                       E  onStop:chatMsgs大小:[com.example.ai.pojo.ChatMsg@5cea5a9]
2023-05-22 20:20:44.146  8425-8425  TAG                     com.example.ai                       E  跑到onStop
2023-05-22 20:20:44.146  8425-8425  HomeFragment TAG:       com.example.ai                       E  onStop:chatMsgs大小:[com.example.ai.pojo.ChatMsg@5cea5a9]
2023-05-22 20:20:44.150  8425-8425  TAG                     com.example.ai                       E  跑到onDestroyView
2023-05-22 20:20:44.150  8425-8425  TAG                     com.example.ai                       E  destroyedCount次数0
2023-05-22 20:20:44.152  8425-8425  TAG                     com.example.ai                       E  跑到onDestroyView
2023-05-22 20:20:44.152  8425-8425  TAG                     com.example.ai                       E  destroyedCount次数0
2023-05-22 20:20:44.288  8425-8425  HomeFragment TAG:       com.example.ai                       E  没有数据,只显示提示语
2023-05-22 20:20:44.288  8425-8425  HomeFragment TAG:       com.example.ai                       E  onCreateView中
2023-05-22 20:20:44.307  8425-8425  HomeFragment TAG:       com.example.ai                       E  没有数据,只显示提示语
2023-05-22 20:20:44.308  8425-8425  HomeFragment TAG:       com.example.ai                       E  onCreateView中
2023-05-22 20:20:44.348  8425-8425  HomeFragment TAG:       com.example.ai                       E  没有数据,只显示提示语
2023-05-22 20:20:44.348  8425-8425  HomeFragment TAG:       com.example.ai                       E  onCreateView中
2023-05-22 20:20:44.368  8425-8425  TAG                     com.example.ai                       E  跑到onStart
2023-05-22 20:20:44.368  8425-8425  HomeFragment TAG:       com.example.ai                       E  onStart:chatMsgs大小:[com.example.ai.pojo.ChatMsg@7ddb2b]
2023-05-22 20:20:44.368  8425-8425  HomeFragment TAG:       com.example.ai                       E  进入了回调中,msgList数量:1
2023-05-22 20:20:44.368  8425-8425  TAG                     com.example.ai                       E  跑到onStart
2023-05-22 20:20:44.368  8425-8425  HomeFragment TAG:       com.example.ai                       E  onStart:chatMsgs大小:[com.example.ai.pojo.ChatMsg@f2b146]
2023-05-22 20:20:44.368  8425-8425  HomeFragment TAG:       com.example.ai                       E  进入了回调中,msgList数量:1
2023-05-22 20:20:44.369  8425-8425  TAG                     com.example.ai                       E  跑到onStart
2023-05-22 20:20:44.369  8425-8425  HomeFragment TAG:       com.example.ai                       E  onStart:chatMsgs大小:[com.example.ai.pojo.ChatMsg@8628b59]
2023-05-22 20:20:44.369  8425-8425  HomeFragment TAG:       com.example.ai                       E  进入了回调中,msgList数量:1
2023-05-22 20:20:44.372  8425-8425  HomeFragment TAG:       com.example.ai                       E  跑到onResume
2023-05-22 20:20:44.372  8425-8425  HomeFragment TAG:       com.example.ai                       E  onResume:chatMsgs大小:[com.example.ai.pojo.ChatMsg@5cea5a9]
2023-05-22 20:20:44.373  8425-8425  HomeFragment TAG:       com.example.ai                       E  跑到onResume
2023-05-22 20:20:44.373  8425-8425  HomeFragment TAG:       com.example.ai                       E  onResume:chatMsgs大小:[com.example.ai.pojo.ChatMsg@5cea5a9]
2023-05-22 20:20:44.373  8425-8425  HomeFragment TAG:       com.example.ai                       E  跑到onResume
2023-05-22 20:20:44.373  8425-8425  HomeFragment TAG:       com.example.ai                       E  onResume:chatMsgs大小:[com.example.ai.pojo.ChatMsg@5cea5a9]
2023-05-22 20:20:49.322  1597-2753  OplusPowerMonitor       system_server                        D  OplusWakeLockInfo{binderhash=40607626flags=1, tag=MicroMsg.MMAutoAuth, duration=786, starttime=25485184, packageName='com.tencent.mm', uid=10271, pid=9737}
2023-05-22 20:20:49.322  1597-2753  OplusPowerMonitor       system_server                        D  OplusWakeLockInfo{binderhash=38330158flags=1, tag=PlatformComm, duration=877, starttime=25485184, packageName='com.tencent.mm', uid=10271, pid=9737}

 可以看到有进入到onChanged函数中,此时可以随便更新你的UI

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mero技术博客

创作不易,打赏小弟可否

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值