diff --git a/app/src/main/java/io/legado/app/ui/main/MainActivity.kt b/app/src/main/java/io/legado/app/ui/main/MainActivity.kt index cf4a2329d..a1a9cdd76 100644 --- a/app/src/main/java/io/legado/app/ui/main/MainActivity.kt +++ b/app/src/main/java/io/legado/app/ui/main/MainActivity.kt @@ -7,18 +7,18 @@ import android.view.MenuItem import androidx.appcompat.app.ActionBarDrawerToggle import androidx.core.view.GravityCompat import androidx.drawerlayout.widget.DrawerLayout -import androidx.lifecycle.ViewModelProvider import com.google.android.material.navigation.NavigationView import io.legado.app.R import io.legado.app.base.BaseActivity import io.legado.app.ui.search.SearchActivity +import io.legado.app.utils.getViewModel import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.app_bar_main.* -import kotlinx.android.synthetic.main.view_titlebar.* class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedListener { override val viewModel: MainViewModel - get() = ViewModelProvider.AndroidViewModelFactory.getInstance(application).create(MainViewModel::class.java) + get() = getViewModel(MainViewModel::class.java) + override val layoutID: Int get() = R.layout.activity_main diff --git a/app/src/main/java/io/legado/app/ui/search/SearchActivity.kt b/app/src/main/java/io/legado/app/ui/search/SearchActivity.kt index 14994c535..27a8450d8 100644 --- a/app/src/main/java/io/legado/app/ui/search/SearchActivity.kt +++ b/app/src/main/java/io/legado/app/ui/search/SearchActivity.kt @@ -1,15 +1,15 @@ package io.legado.app.ui.search import android.os.Bundle -import androidx.lifecycle.ViewModelProvider import io.legado.app.R import io.legado.app.base.BaseActivity -import io.legado.app.help.LayoutManager +import io.legado.app.search.SearchDataBinding +import io.legado.app.utils.getViewModel class SearchActivity : BaseActivity() { override val viewModel: SearchViewModel - get() = ViewModelProvider.AndroidViewModelFactory.getInstance(application).create(SearchViewModel::class.java) + get() = getViewModel(SearchViewModel::class.java) override val layoutID: Int get() = R.layout.activity_search diff --git a/app/src/main/java/io/legado/app/utils/ViewModelExtensions.kt b/app/src/main/java/io/legado/app/utils/ViewModelExtensions.kt new file mode 100644 index 000000000..ed963ec8e --- /dev/null +++ b/app/src/main/java/io/legado/app/utils/ViewModelExtensions.kt @@ -0,0 +1,12 @@ +package io.legado.app.utils + +import androidx.appcompat.app.AppCompatActivity +import androidx.fragment.app.Fragment +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProviders + +fun AppCompatActivity.getViewModel(clazz: Class) = ViewModelProviders.of(this).get(clazz) + +fun Fragment.getViewModel(clazz: Class) = ViewModelProviders.of(this).get(clazz) + +fun Fragment.getViewModelOfActivity(clazz: Class) = ViewModelProviders.of(requireActivity()).get(clazz)