溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Android?Jetpack組件中LiveData的優(yōu)劣是什么

發(fā)布時間:2023-05-09 16:00:34 來源:億速云 閱讀:133 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹了Android Jetpack組件中LiveData的優(yōu)劣是什么的相關(guān)知識,內(nèi)容詳細(xì)易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇Android Jetpack組件中LiveData的優(yōu)劣是什么文章都會有所收獲,下面我們一起來看看吧。

LiveData和ViewModel的關(guān)系

在 ViewModel 中的數(shù)據(jù)發(fā)生變化時,LiveData通知頁面。LiveData 是要和 ViewModel 一起使用的。

Android?Jetpack組件中LiveData的優(yōu)劣是什么

LiveData的優(yōu)勢

Android?Jetpack組件中LiveData的優(yōu)劣是什么確保界面符合數(shù)據(jù)狀態(tài)

Android?Jetpack組件中LiveData的優(yōu)劣是什么不會發(fā)生內(nèi)存泄漏

Android?Jetpack組件中LiveData的優(yōu)劣是什么不會因 Activity 停止而導(dǎo)致崩潰

Android?Jetpack組件中LiveData的優(yōu)劣是什么不再需要手動處理生命周期

Android?Jetpack組件中LiveData的優(yōu)劣是什么數(shù)據(jù)始終保持最新狀態(tài)

Android?Jetpack組件中LiveData的優(yōu)劣是什么適當(dāng)?shù)呐渲酶?/p>

Android?Jetpack組件中LiveData的優(yōu)劣是什么共享資源

demo演示

Android?Jetpack組件中LiveData的優(yōu)劣是什么

使用 ViewModel + LiveData, 實現(xiàn) Fragment 的通信。上面演示界面的兩個seekBar,分別位于兩個 Fragment 中(FirstFragment/SecondFragment, 都在 MainActivity 中),我們要實現(xiàn)拖動其中任何一個seekBar,另外一個seekBar 的值也會隨之改變。即要實現(xiàn)兩個 Fragment 之間的通信。

activity_main.xml

<?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">
    <fragment
        android:id="@+id/first_fragment"
        android:name="com.example.livedata2.FirstFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/guideline"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />
    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_begin="366dp" />
    <fragment
        android:id="@+id/second_fragment"
        android:name="com.example.livedata2.SecondFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintTop_toBottomOf="@+id/guideline"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        />
</androidx.constraintlayout.widget.ConstraintLayout>

fragment_first.xml / fragment_second.xml(它們兩個布局一樣)

<?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=".SecondFragment">
    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="0dp"
        android:max="100"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

MyViewModel.java

LiveData 類型數(shù)據(jù)是寫在 ViewModel 中的。MutableLiveData 繼承自 LiveData,是它的子類,LiveData 是一個抽象類。

package com.example.livedata2;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class MyViewModel extends ViewModel {
    private MutableLiveData<Integer> progress;
    public MutableLiveData<Integer> getProgress() {
        if (progress == null) {
            progress = new MutableLiveData<>();
            progress.setValue(0);
        }
        return progress;
    }
}

上面代碼定義了一個 LivaData 類型的 progress,通過監(jiān)聽它的值的改變,來動態(tài)改變 view 界面顯示的內(nèi)容。

FirstFragment.java

package com.example.livedata2;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;
import java.util.Objects;
public class FirstFragment extends Fragment {
    private SeekBar seekBar;
    private MyViewModel viewModel;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View root = inflater.inflate(R.layout.fragment_f_irst, container, false);
        seekBar = root.findViewById(R.id.seekBar);
        // TODO 獲取到 MyViewModel 對象
        viewModel = new ViewModelProvider(requireActivity(),
                new ViewModelProvider.AndroidViewModelFactory(requireActivity().getApplication())).get(MyViewModel.class);
        // TODO  監(jiān)聽 (LiveData)progress 數(shù)據(jù)的改變
        viewModel.getProgress().observe(requireActivity(), new Observer<Integer>() {
            @Override
            public void onChanged(Integer i) {
                seekBar.setProgress(i);
            }
        });
        // TODO 當(dāng)拖動 seekBar 時,改變 (LiveData)progress 的值
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                viewModel.getProgress().setValue(progress);
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        return root;
    }
}

當(dāng)用戶手動拖動 seekBar 時,SeekBar.setOnSeekBarChangeListener.onProgressChanged() 方法里將拖動的值賦給(LiveData)progress,然后 viewModel.getProgress().observe() 監(jiān)聽(LiveData)progress 值的改變,然后再顯示在 view 上。

FirstFragment.java

SecondFragment 里的內(nèi)容和 FirstFragment 里的內(nèi)容一樣,只是加載的布局不一樣,如下:

View root = inflater.inflate(R.layout.fragment_second, container, false);

因為FirstFragment 與SecondFragment 共用了MyViewModel里的(LiveData)progress,然后顯示在 view 上。所以當(dāng)我拖動任意一個 seekBar 而改變了(LiveData)progress 的值,另外一個 Fragment 的 seekBar 也會隨著改變。從而實現(xiàn)了兩個 Fragment 之間的通信。

MainActivity.java

package com.example.livedata2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

關(guān)于“Android Jetpack組件中LiveData的優(yōu)劣是什么”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“Android Jetpack組件中LiveData的優(yōu)劣是什么”知識都有一定的了解,大家如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI