Android中简单封装Livedata工具类
前言:
之前讲解过livedata和viewmodel的简单使用,也封装过room工具类,本文是对livedata的简单封装和使用,先是封装了一个简单的工具类,然后实现了一个倒计时工具类的封装.
1.LiveDataHelper工具类:
package com.example.livedatautilsdemo.helper;import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;import java.util.Map;
import java.util.WeakHashMap;/*** @author: njb* @date: 2023/7/31 0:10* @desc:*/
public class LiveDataHelper<T>extends MutableLiveData {private final WeakHashMap<Observer<T>, Boolean> mObservers = new WeakHashMap<>();@Overridepublic void observe(@NonNull LifecycleOwner owner, @NonNull Observer observer) {mObservers.put((Observer<T>) observer, true);super.observe(owner, observer);}@Overridepublic void removeObserver(@NonNull Observer observer) {mObservers.remove(observer);super.removeObserver(observer);}@Overridepublic void removeObservers(@NonNull LifecycleOwner owner) {mObservers.clear();super.removeObservers(owner);}public void setValue(Object value) {for (Map.Entry<Observer<T>, Boolean> entry : mObservers.entrySet()) {if (entry.getValue()) {entry.setValue(false);entry.getKey().onChanged((T) value);}}}public void call() {setValue(null);}
}
2.简单使用:
private LiveDataHelper<String> mLiveDataHelper = new LiveDataHelper<>();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();initData();initTime();}private void initView() {tvName = findViewById(R.id.textview);tvTime = findViewById(R.id.tvTime);}private void initData() {mLiveDataHelper.observe(this, new Observer<String>() {@Overridepublic void onChanged(String name) {Log.d("LiveDataDemo", "onChanged: " + name);}});tvName.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {String newName = "NewName" + new Random().nextInt(100);mLiveDataHelper.setValue(newName);Log.d("LiveDataDemo", "onClick: " + newName);tvName.setText(String.format("名称发生变化:%s", newName));}});}
3.布局代码:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><TextViewandroid:id="@+id/textview"android:layout_width="200dp"android:layout_height="60dp"android:text="Hello World!"android:background="@color/design_default_color_primary"android:textSize="20sp"android:textColor="@color/white"android:focusable="true"android:gravity="center"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /><TextViewandroid:id="@+id/tvTime"android:layout_width="200dp"android:layout_height="60dp"android:background="@color/design_default_color_primary"android:text="timer"android:textSize="20sp"android:textColor="@color/white"android:focusable="true"android:gravity="center"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@id/textview"android:layout_marginTop="20dp"/></androidx.constraintlayout.widget.ConstraintLayout>
4.实现效果如下:
5.封装一个倒计时工具类:
package com.example.livedatautilsdemo.helper;import android.os.CountDownTimer;import androidx.lifecycle.MutableLiveData;/*** @author: njb* @date: 2023/8/6 23:37* @desc:*/
public class LiveDataTimeHelper extends MutableLiveData<Long> {private CountDownTimer countDownTimer;public void startCountDown(long millisInFuture, long countDownInterval) {countDownTimer = new CountDownTimer(millisInFuture, countDownInterval) {@Overridepublic void onTick(long millisUntilFinished) {setValue(millisUntilFinished / 1000);}@Overridepublic void onFinish() {setValue(0L);}};countDownTimer.start();}public void stopCountDown() {if (countDownTimer != null) {countDownTimer.cancel();}}@Overrideprotected void onInactive() {super.onInactive();stopCountDown();}
}
6.倒计时Viewmodel:
package com.example.livedatautilsdemo.viewmodel;import android.os.Handler;
import android.os.Looper;
import android.util.Log;import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;import com.example.livedatautilsdemo.helper.LiveDataHelper;
import com.example.livedatautilsdemo.helper.LiveDataTimeHelper;import java.util.Timer;
import java.util.TimerTask;/*** @author: njb* @date: 2023/8/2 23:40* @desc:*/
public class TimerLiveDataViewModel extends ViewModel {private LiveDataTimeHelper liveDataHelper;public LiveDataTimeHelper getCurrentSecondLiveData() {if (liveDataHelper == null) {liveDataHelper = new LiveDataTimeHelper();}return liveDataHelper;}public void startTiming(int seconds) {if (liveDataHelper != null) {liveDataHelper.startCountDown(seconds * 1000, 1000);}}public void stopTiming() {if (liveDataHelper != null) {liveDataHelper.stopCountDown();}}@Overrideprotected void onCleared() {super.onCleared();stopTiming();}
}
7.简单使用:
package com.example.livedatautilsdemo.viewmodel;import android.os.Handler;
import android.os.Looper;
import android.util.Log;import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;import com.example.livedatautilsdemo.helper.LiveDataHelper;
import com.example.livedatautilsdemo.helper.LiveDataTimeHelper;import java.util.Timer;
import java.util.TimerTask;/*** @author: njb* @date: 2023/8/2 23:40* @desc:*/
public class TimerLiveDataViewModel extends ViewModel {private LiveDataTimeHelper liveDataHelper;public LiveDataTimeHelper getCurrentSecondLiveData() {if (liveDataHelper == null) {liveDataHelper = new LiveDataTimeHelper();}return liveDataHelper;}public void startTiming(int seconds) {if (liveDataHelper != null) {liveDataHelper.startCountDown(seconds * 1000, 1000);}}public void stopTiming() {if (liveDataHelper != null) {liveDataHelper.stopCountDown();}}@Overrideprotected void onCleared() {super.onCleared();stopTiming();}
}
8.实现效果如下:
9.项目源码如下:
https://gitee.com/jackning_admin/live-data-utils-demo