LiveData
是一種可觀察的數據存儲器類。與常規的可觀察類不同,LiveData 具有生命週期感知能力,意指它遵循其他應用組件(如 Activity、Fragment 或 Service)的生命週期。這種感知能力可確保 LiveData 僅更新處於活躍生命週期狀態的應用組件觀察者。
下面這個較爲簡單的示例將展示如何使用LiveData。
創建ViewModel
LiveData一般跟ViewModel結合一起用,關於ViewModel的介紹可以看我的另外一篇文章Android ViewModel的使用。
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class DataViewModel extends ViewModel {
private MutableLiveData<String> name;
private MutableLiveData<Integer> age;
public MutableLiveData<String> getName() {
if (name == null) {
name = new MutableLiveData<String>();
//獲取初始值的操作,否則默認爲""。
name.setValue("JohnLiu");//看需求,可以換成進行網絡請求來下載數據
}
return name;
}
public MutableLiveData<Integer> getAge() {
if (age == null) {
age = new MutableLiveData<Integer>();
//獲取初始值的操作,否則默認爲0。
age.setValue(24);
}
return age;
}
}
在Activity中對LiveData進行觀察。
創建觀察數據的Activity,裏面用到的ViewModelUtils這個類的代碼可在Android ViewModel的使用這篇文章裏查看(如果用該類的getPrivateViewModel()方法的話就實現不了效果,原因可以看兩種方法的區別說明。)
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.jetpackdemo.R;
public class LiveDataActivity extends AppCompatActivity {
private DataViewModel dataViewModel;
private TextView tv_name,tv_age;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live_data);
tv_name = findViewById(R.id.tv_name);
tv_age =findViewById(R.id.tv_age);
dataViewModel = ViewModelUtils.getViewModel(this, DataViewModel.class);
// dataViewModel = ViewModelUtils.getPrivateViewModel(this, DataViewModel.class,this);
//觀察name值的變化
dataViewModel.getName().observe(this, new Observer<String>() {
@Override
public void onChanged(String s) {
Log.d("JohnLiu","nameChange");
tv_name.setText(s);
}
});
//觀察age值的變化
dataViewModel.getAge().observe(this, new Observer<Integer>() {
@Override
public void onChanged(Integer integer) {
Log.d("JohnLiu","ageChange");
tv_age.setText(String.valueOf(integer));
}
});
findViewById(R.id.bt).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(LiveDataActivity.this, UpdateValueActivity.class);
startActivity(intent);
}
});
}
}
及其佈局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".livedata.LiveDataActivity"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/bt"
android:text="賦值"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="name當前值爲:"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv_name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="age當前值爲:"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv_age"/>
</LinearLayout>
修改LiveData的數據
這裏只是爲了方便演示在別的Activity修改LiveData的值的效果。關鍵的設值就只有dataViewModel.getAge().setValue(Integer.valueOf(charSequence.toString()));
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import com.jetpackdemo.R;
public class UpdateValueActivity extends AppCompatActivity {
private DataViewModel dataViewModel;
private EditText et_name,et_age;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_value);
dataViewModel =ViewModelUtils.getViewModel(this, DataViewModel.class);
// dataViewModel = ViewModelUtils.getPrivateViewModel(this, DataViewModel.class,this);
et_name = findViewById(R.id.et_name);
et_name.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
dataViewModel.getName().setValue(charSequence.toString());
}
@Override
public void afterTextChanged(Editable editable) {
}
});
et_age = findViewById(R.id.et_age);
et_age.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
dataViewModel.getAge().setValue(Integer.valueOf(charSequence.toString()));
}
@Override
public void afterTextChanged(Editable editable) {
}
});
}
}
效果圖
剛進入到這個模塊,name和age爲初始值。
點擊賦值,跳轉到另外一個頁面修改他們的值。
然後返回上一個頁面,Observer收到值變化的通知,onChanged方法觸發。可以看到name和age的值已經刷新到頁面上