Android ViewModel,在计时器内更新 LiveData
创始人
2024-08-19 04:30:07
0

要在计时器内更新LiveData,您可以使用Android的ViewModel和CountDownTimer类。下面是一个示例代码,演示如何在计时器内更新LiveData:

首先,创建一个包含LiveData和CountDownTimer的ViewModel类。ViewModel类用于在配置更改时保持数据的一致性,并在活动被销毁和重新创建时保持数据的状态。

public class TimerViewModel extends ViewModel {
    private MutableLiveData timeLiveData;
    private CountDownTimer countDownTimer;
    
    public LiveData getTimeLiveData() {
        if (timeLiveData == null) {
            timeLiveData = new MutableLiveData<>();
        }
        return timeLiveData;
    }
    
    public void startTimer(long duration) {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        
        countDownTimer = new CountDownTimer(duration, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                timeLiveData.setValue(millisUntilFinished / 1000);
            }
            
            @Override
            public void onFinish() {
                timeLiveData.setValue(0L);
            }
        };
        
        countDownTimer.start();
    }
    
    @Override
    protected void onCleared() {
        super.onCleared();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }
}

然后,在活动中使用ViewModel来观察LiveData的更改,并在计时器内更新UI:

public class MainActivity extends AppCompatActivity {
    private TimerViewModel timerViewModel;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        timerViewModel = ViewModelProviders.of(this).get(TimerViewModel.class);
        LiveData timeLiveData = timerViewModel.getTimeLiveData();
        timeLiveData.observe(this, new Observer() {
            @Override
            public void onChanged(Long time) {
                // 在这里更新UI,显示剩余时间
                // textView.setText(String.valueOf(time));
            }
        });
        
        // 启动计时器
        long duration = 60000; // 1分钟
        timerViewModel.startTimer(duration);
    }
}

这样,每次计时器的时间发生变化时,LiveData的观察者将收到通知,并更新UI。请注意,您可以根据自己的需求自定义计时器的逻辑和UI更新。

相关内容

热门资讯

值得注意的是!wepoker免... 值得注意的是!wepoker免费透视(透视)新上游辅助(好像有辅助工具)-哔哩哔哩1、首先打开新上游...
透视讲解!wepoker科技辅... 透视讲解!wepoker科技辅助器(透视)江西中至黑科技辅助软件(总是有辅助辅助器)-哔哩哔哩一、江...
透视中牌率!hhpoker德州... 透视中牌率!hhpoker德州透视挂(透视)潮汕激k脚本(果然是有辅助平台)-哔哩哔哩1、上手简单,...
透视好友房!竞技联盟透视插件(... 透视好友房!竞技联盟透视插件(透视)涂山山西辅助(本来真的有辅助辅助器)-哔哩哔哩1、涂山山西辅助透...
据了解!拱趴大菠萝十三水作必弊... 据了解!拱趴大菠萝十三水作必弊(透视)微信小程序辅助工具(其实是真的辅助软件)-哔哩哔哩1、用户打开...
透视讲解!约局吧德州有挂吗(透... 透视讲解!约局吧德州有挂吗(透视)多乐跑胡子辅助(一直是真的辅助平台)-哔哩哔哩1、让任何用户在无需...
透视脚本!wpk辅助(透视)7... 透视脚本!wpk辅助(透视)789大菠萝有挂吗(确实有辅助安装)-哔哩哔哩1、透视脚本!wpk辅助(...
透视挂!wepoker有透视功... 透视挂!wepoker有透视功能吗(透视)微信小程序微乐家乡辅助器(都是真的是有辅助软件)-哔哩哔哩...
近日!wepoker破解器有用... 近日!wepoker破解器有用吗(透视)福建天天开心辅助工具下载(果然有辅助下载)-哔哩哔哩1、完成...
透视总结!hhpoker一直输... 透视总结!hhpoker一直输有挂吗(透视)开心庄园辅助器免费(一直真的是有辅助平台)-哔哩哔哩1、...