Android之ViewModel的使用

Android中的ViewModel是一個可以用來存儲UI相關(guān)的數(shù)據(jù)的類。ViewModel的生命周期會比創(chuàng)建它的Activity、Fragment的生命周期長。

這里拿官方的一張圖:

ViewModel-Lifecycle

這張圖是在在沒任何設(shè)置屏幕發(fā)生轉(zhuǎn)換Activity的生命周期變化和ViewModel的生命周期。可以看重建的時候,ViewModel中的數(shù)據(jù)是不會被清理的。

借助于上面這一特點,ViewModel有下面的兩個優(yōu)點:

  • Activity進行重建的時候,ViewModel的數(shù)據(jù)不會被回收調(diào)用。這時候我們就可以不用通過onSaveInstanceState()方法來進行數(shù)據(jù)的存儲了。而且用onSaveInstanceState()方法為了使Activity能夠盡快的重建還只能存儲少量的數(shù)據(jù)進行恢復(fù)。
  • Activity中通常會有有那種在其創(chuàng)建的時候獲取數(shù)據(jù),然后在其銷毀的時候釋放數(shù)據(jù)的方法。如果這些放在Activity中的話,在Activity進行重建的時候,會很浪費資源。但是如果方法在ViewModel中的話,Activity的重建將不會導(dǎo)致數(shù)據(jù)的重復(fù)獲取。

當(dāng)然,屏幕的旋轉(zhuǎn),你也可以通過configChanges的設(shè)置來阻止它的重建。但是其它的有些意外情況Activity也是有可能重建的

ViewModel的使用

其實,ViewModel的使用在前面的LiveData例子中就有相應(yīng)的體現(xiàn)。這篇博客就寫一個通過ViewModel來實現(xiàn)Fragment之間通信的例子吧!

先進行ViewModel的創(chuàng)建
class SharedViewModel : ViewModel() {
    var sharedName:MutableLiveData<String> = MutableLiveData()
    
    init {
        sharedName.value = "anriku"
    }
}

這個ViewModel創(chuàng)建得很簡單,就是自定義一個SharedViewModel繼承自ViewModel。這里ViewModel中包含一個LiveData對象。關(guān)于ViewModel更難一些內(nèi)容將在后面進行介紹。

再進行OneFragment的創(chuàng)建

xml如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/bt_fragment_one"
        android:text="改變SharedViewModel的值"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

這個Fragment的xml很簡單,就只有一個Button控件。這個Button控件是用來改變ViewModel的值的。然后在TwoFragment中體現(xiàn)改變的值。

OneFragment的代碼如下:

class OneFragment: Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, 
                              savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_one, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val model = ViewModelProviders.of(activity!!).get(SharedViewModel::class.java)

        bt_fragment_one.setOnClickListener{
            model.sharedName.value = "anrikuwen"
        }
    }

    override fun onDestroy() {
        Toast.makeText(activity,"OneFragment is destroyed", Toast.LENGTH_SHORT).show()
        super.onDestroy()
    }
}

這里OneFragment中我們通過ViewModelProviders.of(activity!!).get(SharedViewModel::class.java)來進行SharedViewModel的獲取,這里需要注意的就是of的參數(shù)給的是Fragment所綁定的Activity,因此它的生命周期就以Fragment綁定的Activity作為參照對象了。Fragment的創(chuàng)建銷毀對SharedViewModel沒有任何影響。

然后Button控件設(shè)置監(jiān)聽器,使其按一下后改變SharedViewModel中的sharedName的值。

再進行TwoFragment的創(chuàng)建

xml如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

沒看錯,依然如此的清新。就是一個TextView控件在里面。用于顯示ShanredViewModel中的屬性的值。

下面是TwoFragment的代碼:

class TwoFragment: Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, 
    savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_two,container,false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val model = ViewModelProviders.of(activity!!).get(SharedViewModel::class.java)

        model.sharedName.observe(this, Observer {
            tv_fragment_two.text = it
        })
    }

    override fun onDestroy() {
        Toast.makeText(activity, "TwoFragment is destroyed", Toast.LENGTH_SHORT).show()
        super.onDestroy()
    }
}

這里獲取SharedViewModel的方式和OneFragment是一樣的。

但是在TwoFragment中,我們給SharedViewModel中的LiveData屬性設(shè)置了一個Observer對象,在其數(shù)據(jù)發(fā)生了變化之后,如果TwoFragment處于活躍狀態(tài)的話就進行改變,不活躍就會等其活躍之后再進行對應(yīng)的UI變化。

最后看看用來管理這兩個Fragment的Activity
<?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=".viewmodel.ViewModelActivity">

    <Button
        android:id="@+id/bt_one"
        android:layout_width="0dp"
        android:text="切換OneFragment"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@id/bt_two"
        app:layout_constraintRight_toRightOf="parent"/>

    <Button
        android:id="@+id/bt_two"
        android:layout_width="0dp"
        android:text="切換TwoFragment"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toTopOf="@id/fl"
        app:layout_constraintTop_toBottomOf="@id/bt_one"/>

    <FrameLayout
        android:id="@+id/fl"
        android:layout_width="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@id/bt_two"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_height="0dp">

    </FrameLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

上面xml沒啥難點。這里的兩個Button分別用來顯示對應(yīng)的Fragment的。FramLayout用來顯示Fragment的。

再來看看Activity中的代碼:

class ViewModelActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_view_model)

        replaceFragment(TwoFragment())
        
        bt_one.setOnClickListener{
            replaceFragment(OneFragment())
        }
        bt_two.setOnClickListener{
            replaceFragment(TwoFragment())
        }
    }

    private fun replaceFragment(fragment: Fragment){
        val fragmentManager = supportFragmentManager
        val transaction = fragmentManager.beginTransaction()
        transaction.replace(R.id.fl,fragment)
        transaction.commit()
    }

    override fun onDestroy() {
        Log.e("ViewModelActivity", "onDestroy")
        super.onDestroy()
    }
}

對現(xiàn)在在學(xué)習(xí)ViewModel的你上面代碼沒啥問題吧,就是Fragment之間的轉(zhuǎn)換邏輯。

OK,萬事俱備了?,F(xiàn)在自己來試試吧!在OneFragment對其SharedViewModel的值進行改變。然后再切換到TwoFragment中。當(dāng)當(dāng)當(dāng)?。。≥p松的就實現(xiàn)了Fragment之間的通信了吧!

構(gòu)造器有參數(shù)的ViewModel

當(dāng)我們的ViewModel需要進行構(gòu)造器需要穿參數(shù)的時候,就不能像上面一樣進行實例化了。而需要借助于ViewModelProvider的Fatory來進行構(gòu)造。

下面是對前面的SharedViewModel進行修改的代碼:

class SharedViewModel(sharedName: String) : ViewModel() {
    var sharedName: MutableLiveData<String> = MutableLiveData()

    init {
        this.sharedName.value = sharedName
    }

    class SharedViewModelFactory(private val sharedName: String) : 
    ViewModelProvider.Factory {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            return SharedViewModel(sharedName) as T
        }
    }
}

可以看到在SharedViewModel有一個內(nèi)部類基礎(chǔ)自ViewModelProvider.Factory接口。并重寫了create方法。這個方法返回一個ViewModel這里我們就是要實例化SharedViewModel對象,因此這里返回一個SharedViewModel對象,可以看到參數(shù)這時候就通過SharedViewModelFactory傳給了SharedViewModel了。

這時候不光是SharedViewModel要進行修改,在進行SharedViewModel的獲取的時候也是需要進行相應(yīng)的修改的。

前面兩個Fragment獲取SharedViewModel部分的代碼都要改成如下代碼:

val model = ViewModelProviders.of(activity!!, SharedViewModel.SharedViewModelFactory("anriku")).get(SharedViewModel::class.java)

其實就是在獲取ViewModelProvider對象的of方法有修改。這里用的是帶有Factory的of方法。傳入剛才在SharedViewmodel中寫的Factory的實例。

AndroidViewModel

使用ViewModel的時候,需要注意的是ViewModel不能夠持有View、Lifecycle、Acitivity引用,而且不能夠包含任何包含前面內(nèi)容的類。因為這樣很有可能會造成內(nèi)存泄漏。

那如果需要使用Context對象改怎么辦。這時候我們可以給ViewModel一個Application。Application是一個Context,而且一個應(yīng)用也只會有Application。

我們自己添加Application?其實沒必要Google還有一個AndroidViewModel。這是一個包含Application的ViewModel。

下面是一個AndroidViewModel的源碼:

public class AndroidViewModel extends ViewModel {
    @SuppressLint("StaticFieldLeak")
    private Application mApplication;

    public AndroidViewModel(@NonNull Application application) {
        mApplication = application;
    }

    /**
     * Return the application.
     */
    @SuppressWarnings("TypeParameterUnusedInFormals")
    @NonNull
    public <T extends Application> T getApplication() {
        //noinspection unchecked
        return (T) mApplication;
    }
}

可以看到只是在ViewModel的基礎(chǔ)上添加了Application。

總結(jié)

這篇博客主要講解了ViewModel構(gòu)造參數(shù)有參數(shù)以及無參數(shù)情況下的創(chuàng)建。并且通過一個例子,看到了ViewModel如何輕易的實現(xiàn)Fragment之間的通信的。

參考

官方文檔

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容