Android Kotlin+Jetpack+MVVM

開篇廢話

最近學(xué)習(xí)了Kotlin僵腺,學(xué)習(xí)了Jetpack,發(fā)現(xiàn)是真香壶栋,所以就手寫了一個MVVM的框架辰如,可以方便開發(fā)。Kotlin+Jetpack+MVVM之GitHub地址贵试,幫我點個Star琉兜,贈人玫瑰凯正,手留余香,謝謝呕童。

先講一下思路

ViewModel

ViewModel可以放一些數(shù)據(jù)和網(wǎng)絡(luò)請求漆际,通過LiveData回調(diào)給V層數(shù)據(jù),因為LiveData會傳入Lifecycle夺饲,可以防止內(nèi)存泄漏奸汇。

Activity & Fragment

V層可以通過ViewModelStore拿到相應(yīng)作用域的ViewModel畔师,通過ViewModel去獲取數(shù)據(jù)她倘。

其它

同時簡單封裝了幾個網(wǎng)絡(luò)請求之后V層比較關(guān)心的請求結(jié)果的成功失敗以及列表是否還有更多數(shù)據(jù)。
還封裝了一個LiveData的擴展函數(shù)省有,減少V層邏輯浩销,使代碼更清晰贯涎。

上核心代碼

對ViewModel進行封裝

package com.cc.mvvm.mvvm

import android.os.Bundle
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel

/**
 * Created by guoshichao on 2021/2/20
 * MVVM BaseModel
 */
abstract class BaseViewModel : ViewModel() {

    val loadStateLiveData = MutableLiveData<LoadState>()
    val hasMoreStateLiveData = MutableLiveData<HasMoreState>()

    open fun init(arguments: Bundle?) {}

    /**
     * 加載數(shù)據(jù)開始  用調(diào)用V層的loadStart
     */
    protected fun loadStart() {
        loadStateLiveData.value = LoadState.LoadStart
    }

    /**
     * 加載數(shù)據(jù)結(jié)束  用調(diào)用V層的loadFinish
     */
    protected fun loadFinish(success: Boolean) {
        if (success) {
            loadStateLiveData.setValue(LoadState.LoadSuccess)
        } else {
            loadStateLiveData.setValue(LoadState.LoadFail)
        }
    }

    /**
     * 是否有更多數(shù)據(jù)  用調(diào)用V層的HasMore和noMore
     */
    protected fun hasMore(hasMore : Boolean){
        if (hasMore) {
            hasMoreStateLiveData.value = HasMoreState.HasMore
        } else {
            hasMoreStateLiveData.value = HasMoreState.NoMore
        }
    }

    override fun onCleared() {
        Log.v("BaseViewModel", this.javaClass.name + this + " onCleared()")
        super.onCleared()
    }

}

對Activity進行封裝

package com.cc.mvvm.mvvm

import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import androidx.viewbinding.ViewBinding
import com.cc.mvvm.base.BaseActivity
import java.lang.reflect.ParameterizedType

/**
 * Created by guoshichao on 2021/2/20
 * MVVM BaseActivity
 */
abstract class MVVMBaseActivity<V : ViewBinding, M : BaseViewModel> : BaseActivity() {

    protected lateinit var mViewBinding: V

    protected lateinit var mViewModel: M

    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        onPrepare()
        mViewBinding = getViewBinding()
        setContentView(mViewBinding.root)
        mViewModel = getViewModel()!!
        mViewModel.init(if (intent != null) intent.extras else null)
        loadState()
        onRegisterLiveListener()
        liveDataObserver()
        init()
    }

    /**
     * 預(yù)配置
     */
    protected open fun onPrepare() {}

    /**
     * 獲取ViewBinding
     */
    abstract fun getViewBinding(): V

    /**
     * 返回ViewModelStoreOwner
     */
    protected open fun getViewModelStoreOwner() : ViewModelStoreOwner {
        return this
    }

    /**
     * 獲取ViewModel
     */
    protected open fun getViewModel(): M? {
        //這里獲得到的是類的泛型的類型
        val type = javaClass.genericSuperclass
        if (type != null && type is ParameterizedType) {
            val actualTypeArguments = type.actualTypeArguments
            val tClass = actualTypeArguments[1]
            return ViewModelProvider(getViewModelStoreOwner(),
                    ViewModelProvider.AndroidViewModelFactory.getInstance(application))
                    .get(tClass as Class<M>)
        }
        return null
    }

    /**
     * LiveEventBus的Listener
     */
    protected open fun onRegisterLiveListener() {}

    /**
     * LiveData的Observer
     */
    protected abstract fun liveDataObserver()

    /**
     * 回調(diào)刷新控件狀態(tài)
     */
    private fun loadState() {
        mViewModel.loadStateLiveData.observe(this, Observer {
            when (it) {
                LoadState.LoadStart -> loadStart()
                LoadState.LoadSuccess -> loadFinish(true)
                LoadState.LoadFail -> loadFinish(false)
            }
        })
        mViewModel.hasMoreStateLiveData.observe(this, Observer {
            when (it) {
                HasMoreState.HasMore -> hasMore()
                HasMoreState.NoMore -> noMore()
            }
        })
    }

    /**
     * 初始化
     */
    protected abstract fun init()

    //加載開始
    protected open fun loadStart() {}

    //加載結(jié)束
    protected open fun loadFinish(success: Boolean) {}

    //有下一頁
    protected open fun hasMore() {}

    //無下一頁
    protected open fun noMore() {}

}

對Fragment進行封裝

package com.cc.mvvm.mvvm

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import androidx.viewbinding.ViewBinding
import com.cc.mvvm.base.BaseFragment
import java.lang.reflect.ParameterizedType

/**
 * Created by guoshichao on 2021/2/20
 * MVVM BaseFragment
 */
abstract class MVVMBaseFragment<V : ViewBinding, M : BaseViewModel> : BaseFragment() {

    protected lateinit var mViewBinding: V

    protected lateinit var mViewModel: M

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        onPrepare()
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        mViewBinding = getViewBinding()

        return mViewBinding.root
    }

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

    private fun load() {
        mViewModel = getViewModel()!!
        mViewModel.init(arguments)
        loadState()
        onRegisterLiveListener()
        liveDataObserver()
        init()
    }

    /**
     * 預(yù)配置
     */
    protected open fun onPrepare() {}

    /**
     * 獲取ViewBinding
     */
    abstract fun getViewBinding(): V

    /**
     * 返回ViewModelStoreOwner
     */
    protected open fun getViewModelStoreOwner() : ViewModelStoreOwner {
        return this
    }

    /**
     * 獲取ViewModel
     */
    protected open fun getViewModel(): M? {
        //這里獲得到的是類的泛型的類型
        val type = javaClass.genericSuperclass
        if (type != null && type is ParameterizedType) {
            val actualTypeArguments = type.actualTypeArguments
            val tClass = actualTypeArguments[1]
            return ViewModelProvider(getViewModelStoreOwner(),
                    ViewModelProvider.AndroidViewModelFactory.getInstance(activity!!.application))
                    .get(tClass as Class<M>)
        }
        return null
    }

    /**
     * LiveEventBus的Listener
     */
    protected open fun onRegisterLiveListener() {}

    /**
     * LiveData的Observer
     */
    protected abstract fun liveDataObserver()

    /**
     * 初始化
     */
    protected abstract fun init()

    /**
     * 回調(diào)刷新控件狀態(tài)
     */
    private fun loadState() {
        mViewModel.loadStateLiveData.observe(viewLifecycleOwner, Observer {
            when (it) {
                LoadState.LoadStart -> loadStart()
                LoadState.LoadSuccess -> loadFinish(true)
                LoadState.LoadFail -> loadFinish(false)
            }
        })
        mViewModel.hasMoreStateLiveData.observe(viewLifecycleOwner, Observer {
            when (it) {
                HasMoreState.HasMore -> hasMore()
                HasMoreState.NoMore -> noMore()
            }
        })
    }

    //加載開始
    protected open fun loadStart() {}

    //加載結(jié)束
    protected open fun loadFinish(success: Boolean) {}

    //有下一頁
    protected open fun hasMore() {}

    //無下一頁
    protected open fun noMore() {}

}

其它封裝

LoadState的封裝

package com.cc.mvvm.mvvm

enum class LoadState {
    LoadStart, LoadSuccess, LoadFail
}

HasMoreState的封裝

package com.cc.mvvm.mvvm

enum class HasMoreState {
    HasMore, NoMore
}

LiveData擴展函數(shù)封裝

package com.cc.mvvm.mvvm

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer

fun <T> LifecycleOwner.observe(liveData: LiveData<T>, observer: (t: T) -> Unit) {
    liveData.observe(this, Observer { it?.let { t -> observer(t) } })
}

BaseActivity & BaseFragment

大家可以直接繼承自己項目中的BaseActivity和BaseFragment,也可以使用我的慢洋,主要是加了一些Log塘雳,方便觀察bug及數(shù)據(jù)等。
BaseActivity

package com.cc.mvvm.base;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created by guoshichao on 2021/4/28
 */
public class BaseActivity extends AppCompatActivity {

    protected void onCreate(Bundle args) {
        if (Build.VERSION.SDK_INT == 26 && this.isTranslucentOrFloating()) {
            boolean result = this.fixOrientation();
            Log.i("BaseActivity", "onCreate fixOrientation when Oreo, result = " + result);
        }

        super.onCreate(args);
        Log.v("BaseActivity", this.getClass().getName() + " onCreate()");
    }

    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.v("BaseActivity", this.getClass().getName() + " onSaveInstanceState()");
    }

    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Log.v("BaseActivity", this.getClass().getName() + " onRestoreInstanceState()");
    }

    protected void onStart() {
        super.onStart();
        Log.v("BaseActivity", this.getClass().getName() + " onStart()");
    }

    protected void onResume() {
        super.onResume();
        Log.v("BaseActivity", this.getClass().getName() + " onResume()");
    }

    protected void onPause() {
        super.onPause();
        Log.v("BaseActivity", this.getClass().getName() + " onPause()");
    }

    protected void onStop() {
        super.onStop();
        Log.v("BaseActivity", this.getClass().getName() + " onStop()");
    }

    protected void onDestroy() {
        super.onDestroy();
        Log.v("BaseActivity", this.getClass().getName() + " onCreate()");
    }

    private boolean isTranslucentOrFloating() {
        boolean isTranslucentOrFloating = false;

        try {
            int[] styleableRes = (int[])((int[])Class.forName("com.android.internal.R$styleable").getField("Window").get((Object)null));
            TypedArray ta = this.obtainStyledAttributes(styleableRes);
            Method m = ActivityInfo.class.getMethod("isTranslucentOrFloating", TypedArray.class);
            m.setAccessible(true);
            isTranslucentOrFloating = (Boolean)m.invoke((Object)null, ta);
            m.setAccessible(false);
        } catch (Exception var5) {
            var5.printStackTrace();
        }

        return isTranslucentOrFloating;
    }

    private boolean fixOrientation() {
        try {
            Field field = Activity.class.getDeclaredField("mActivityInfo");
            field.setAccessible(true);
            ActivityInfo o = (ActivityInfo)field.get(this);
            o.screenOrientation = -1;
            field.setAccessible(false);
            return true;
        } catch (Exception var3) {
            var3.printStackTrace();
            return false;
        }
    }

    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.v("BaseActivity", this.getClass().getName() + " onNewIntent()");
    }

}

BaseFragment

package com.cc.mvvm.base;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

/**
 * Created by guoshichao on 2021/4/28
 */
public class BaseFragment extends Fragment {

    public void onAttach(Activity activity) {
        super.onAttach(activity);
        Log.v("BaseFragment", this.getClass().getName() + this + " onAttach()");
    }

    @TargetApi(22)
    public void onAttach(Context context) {
        super.onAttach(context);
        Log.v("BaseFragment", this.getClass().getName() + this + " onAttach()");
    }

    public void onDetach() {
        Log.v("BaseFragment", this.getClass().getName() + this + " onDetach()");
        super.onDetach();
    }

    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.v("BaseFragment", this.getClass().getName() + this + " onCreate()");
    }

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.v("BaseFragment", this.getClass().getName() + this + " onCreateView()");
        View contentView = super.onCreateView(inflater, container, savedInstanceState);
        return contentView;
    }

    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.v("BaseFragment", this.getClass().getName() + this + " setUserVisibleHint(), isVisibleToUser:" + isVisibleToUser);
    }

    public void onStart() {
        super.onStart();
        Log.v("BaseFragment", this.getClass().getName() + this + " onStart()");
    }

    public void onResume() {
        super.onResume();
        Log.v("BaseFragment", this.getClass().getName() + this + " onResume()");
    }

    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.v("BaseFragment", this.getClass().getName() + this + " onSaveInstanceState()");
    }

    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
        Log.v("BaseFragment", this.getClass().getName() + this + " onViewStateRestored()");
    }

    public void onPause() {
        super.onPause();
        Log.v("BaseFragment", this.getClass().getName() + this + " onPause()");
    }

    public void onStop() {
        super.onStop();
        Log.v("BaseFragment", this.getClass().getName() + this + " onStop()");
    }

    public void onDestroyView() {
        super.onDestroyView();
        Log.v("BaseFragment", this.getClass().getName() + this + " onDestroyView()");
    }

    public void onDestroy() {
        super.onDestroy();
        Log.v("BaseFragment", this.getClass().getName() + this + " onDestroy()");
    }

}

使用Demo

V層

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">

    <TextView
        android:id="@+id/tv_hello"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt

package com.cc.kotlin_jetpack_mvvm

import android.widget.Toast
import com.cc.kotlin_jetpack_mvvm.databinding.ActivityMainBinding
import com.cc.mvvm.mvvm.MVVMBaseActivity
import com.cc.mvvm.mvvm.observe

class MainActivity : MVVMBaseActivity<ActivityMainBinding, MainViewModel>() {

    override fun getViewBinding(): ActivityMainBinding {
        return ActivityMainBinding.inflate(layoutInflater)
    }

    override fun liveDataObserver() {
        observe(mViewModel.modelLiveData, ::showToast)
    }

    private fun showToast(message : String) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show()
    }

    override fun init() {
        mViewBinding.tvHello.setOnClickListener{
            mViewModel.getModel()
        }
    }

}

MainViewModel.kt

package com.cc.kotlin_jetpack_mvvm

import androidx.lifecycle.MutableLiveData
import com.cc.mvvm.mvvm.BaseViewModel

/**
 * Created by guoshichao on 2021/4/28
 */
class MainViewModel : BaseViewModel() {

    val modelLiveData = MutableLiveData<String>()

    fun getModel() {
        modelLiveData.value = "Hello!!!"
    }

}

結(jié)束小語

總來來說普筹,封裝的還是比較簡單的败明,因為很多工作Jetpack已經(jīng)幫我們?nèi)ヌ幚砹耍恍枰覀冞^多的去做什么太防。

更多內(nèi)容戳這里(整理好的各種文集)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末妻顶,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子蜒车,更是在濱河造成了極大的恐慌讳嘱,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,294評論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件酿愧,死亡現(xiàn)場離奇詭異沥潭,居然都是意外死亡,警方通過查閱死者的電腦和手機嬉挡,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,493評論 3 385
  • 文/潘曉璐 我一進店門叛氨,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人棘伴,你說我怎么就攤上這事寞埠。” “怎么了焊夸?”我有些...
    開封第一講書人閱讀 157,790評論 0 348
  • 文/不壞的土叔 我叫張陵仁连,是天一觀的道長。 經(jīng)常有香客問我,道長饭冬,這世上最難降的妖魔是什么使鹅? 我笑而不...
    開封第一講書人閱讀 56,595評論 1 284
  • 正文 為了忘掉前任,我火速辦了婚禮昌抠,結(jié)果婚禮上患朱,老公的妹妹穿的比我還像新娘。我一直安慰自己炊苫,他們只是感情好裁厅,可當我...
    茶點故事閱讀 65,718評論 6 386
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著侨艾,像睡著了一般执虹。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上唠梨,一...
    開封第一講書人閱讀 49,906評論 1 290
  • 那天袋励,我揣著相機與錄音,去河邊找鬼当叭。 笑死茬故,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的蚁鳖。 我是一名探鬼主播磺芭,決...
    沈念sama閱讀 39,053評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼才睹!你這毒婦竟也來了徘跪?” 一聲冷哼從身側(cè)響起甘邀,我...
    開封第一講書人閱讀 37,797評論 0 268
  • 序言:老撾萬榮一對情侶失蹤琅攘,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后松邪,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體坞琴,經(jīng)...
    沈念sama閱讀 44,250評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,570評論 2 327
  • 正文 我和宋清朗相戀三年逗抑,在試婚紗的時候發(fā)現(xiàn)自己被綠了剧辐。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,711評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡邮府,死狀恐怖荧关,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情褂傀,我是刑警寧澤忍啤,帶...
    沈念sama閱讀 34,388評論 4 332
  • 正文 年R本政府宣布,位于F島的核電站仙辟,受9級特大地震影響同波,放射性物質(zhì)發(fā)生泄漏鳄梅。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 40,018評論 3 316
  • 文/蒙蒙 一未檩、第九天 我趴在偏房一處隱蔽的房頂上張望戴尸。 院中可真熱鬧,春花似錦冤狡、人聲如沸孙蒙。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,796評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽马篮。三九已至,卻和暖如春怜奖,著一層夾襖步出監(jiān)牢的瞬間浑测,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,023評論 1 266
  • 我被黑心中介騙來泰國打工歪玲, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留迁央,地道東北人。 一個月前我還...
    沈念sama閱讀 46,461評論 2 360
  • 正文 我出身青樓滥崩,卻偏偏與公主長得像岖圈,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子钙皮,可洞房花燭夜當晚...
    茶點故事閱讀 43,595評論 2 350