欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android Jetpack組件中LiveData的優(yōu)劣

 更新時間:2023年04月03日 08:29:04   作者:別偷我的豬_09  
LiveData是Jetpack組件的一部分,更多的時候是搭配ViewModel來使用,相對于Observable,LiveData的最大優(yōu)勢是其具有生命感知的,換句話說,LiveData可以保證只有在組件(?Activity、Fragment、Service)處于活動生命周期狀態(tài)的時候才會更新數據

LiveData和ViewModel的關系

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

LiveData的優(yōu)勢

確保界面符合數據狀態(tài)

不會發(fā)生內存泄漏

不會因 Activity 停止而導致崩潰

不再需要手動處理生命周期

數據始終保持最新狀態(tài)

適當的配置更改

共享資源

demo演示

使用 ViewModel + LiveData, 實現 Fragment 的通信。上面演示界面的兩個seekBar,分別位于兩個 Fragment 中(FirstFragment/SecondFragment, 都在 MainActivity 中),我們要實現拖動其中任何一個seekBar,另外一個seekBar 的值也會隨之改變。即要實現兩個 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 類型數據是寫在 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 界面顯示的內容。

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 數據的改變
        viewModel.getProgress().observe(requireActivity(), new Observer<Integer>() {
            @Override
            public void onChanged(Integer i) {
                seekBar.setProgress(i);
            }
        });
        // TODO 當拖動 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;
    }
}

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

FirstFragment.java

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

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

因為FirstFragment 與SecondFragment 共用了MyViewModel里的(LiveData)progress,然后顯示在 view 上。所以當我拖動任意一個 seekBar 而改變了(LiveData)progress 的值,另外一個 Fragment 的 seekBar 也會隨著改變。從而實現了兩個 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);
    }
}

到此這篇關于Android Jetpack組件中LiveData的優(yōu)劣的文章就介紹到這了,更多相關Android LiveData內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Android RecyclerView使用入門介紹

    Android RecyclerView使用入門介紹

    RecyclerView是Android一個更強大的控件,其不僅可以實現和ListView同樣的效果,還有優(yōu)化了ListView中的各種不足。其可以實現數據縱向滾動,也可以實現橫向滾動(ListView做不到橫向滾動)。接下來講解RecyclerView的用法
    2022-10-10
  • Android?任務棧機制詳解

    Android?任務棧機制詳解

    這篇文章主要為大家介紹了Android?任務棧機制詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-12-12
  • Android Handler leak分析及解決辦法詳解

    Android Handler leak分析及解決辦法詳解

    這篇文章主要介紹了Android Handler leak分析及解決辦法詳解的相關資料,需要的朋友可以參考下
    2017-03-03
  • android imageview圖片居中技巧應用

    android imageview圖片居中技巧應用

    做UI布局,尤其是遇到比較復雜的多重LinearLayout嵌套,常常會被一些比較小的問題困擾上半天,可是無論怎樣設置layout_gravity屬性,都無法達到效果
    2012-11-11
  • Android屏幕及view的截圖實例詳解

    Android屏幕及view的截圖實例詳解

    這篇文章主要介紹了Android屏幕及view的截圖實例詳解的相關資料,需要的朋友可以參考下
    2017-05-05
  • android實現音樂播放器進度條效果

    android實現音樂播放器進度條效果

    這篇文章主要為大家詳細介紹了android實現音樂播放器進度條效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-04-04
  • Android的Launcher啟動器中添加快捷方式及小部件實例

    Android的Launcher啟動器中添加快捷方式及小部件實例

    這篇文章主要介紹了在Android的Launcher啟動器中添加快捷方式及窗口小部件的方法,包括在自己的應用程序中添加窗口小部件AppWidget的例子,需要的朋友可以參考下
    2016-02-02
  • Android實現簡單的撥號器功能

    Android實現簡單的撥號器功能

    這篇文章主要為大家詳細介紹了Android實現簡單的撥號器功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-07-07
  • Android SharedPreferences實現保存登錄數據功能

    Android SharedPreferences實現保存登錄數據功能

    這篇文章主要為大家詳細介紹了Android SharedPreferences實現保存登錄數據功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-05-05
  • Android自定義View實現進度條動畫

    Android自定義View實現進度條動畫

    這篇文章主要為大家詳細介紹了Android自定義View實現進度條動畫,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-08-08

最新評論