标签: android-mvvm

如何让这个 ViewModelFactory 更加灵活并接受不同种类的 ViewModel 类?

我复制了一个带有 Android 架构组件、Retrofit、Dagger 和数据绑定的 MVVM 示例。我使用此代码作为我的应用程序的起点,以便开始在 Android 应用程序开发中使用更好的架构。但是,请使用以下代码:

interface ViewModelInjector {
    /**
     * Injects required dependencies into the specified PostListViewModel.
     * @param postListViewModel PostListViewModel in which to inject the dependencies
     */
    fun inject(postListViewModel: PostListViewModel)

    @Component.Builder
    interface Builder {
        fun build(): ViewModelInjector
        fun networkModule(networkModule: NetworkModule): Builder
    }
}
Run Code Online (Sandbox Code Playgroud)

class ViewModelFactory(private val activity: AppCompatActivity) : ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(PostListViewModel::class.java)) {
            val db = Room.databaseBuilder(
                activity.applicationContext,
                AppDatabase::class.java,
                "posts"
            ).build()

            @Suppress("UNCHECKED_CAST")
            return PostListViewModel(db.postDao()) as …
Run Code Online (Sandbox Code Playgroud)

android android-mvvm android-viewmodel

5
推荐指数
1
解决办法
1634
查看次数

ViewModel + Data Binding中的最佳实践和模式.ViewModel中的ObservableField好吗?

通过示例,我看到了两种使用Android架构组件的MVVM方法.

第一种方法:

  1. ViewModel 提供 LiveData
  2. Activity 订阅 LiveData
  3. 当被叫观察者Activity正在设置数据时ViewModel ObservableField.
  4. 整个ViewModel传递给绑定.
  5. xml你刚刚设置ObservableField为值

    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        app:visibleGone="@{viewmodel.listLoading}"/>
    
    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swiperefresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:refreshing="@{viewmodel.listRefreshing}"
        app:onRefreshListener="@{() -> viewmodel.refreshList()}"
        app:visibleGone="@{!viewmodel.listLoading}">
    
    Run Code Online (Sandbox Code Playgroud)

优点:我并不需要通过状态(例如"加载"),因为我更新listLoading ObservableFieldViewModel为这样的:

val listLoading = ObservableBoolean(false)
/** other observable fields go here **/

val list: MutableLiveData<List<Item>> = MutableLiveData()

  fun loadList() {
        listLoading.set(true)
        repo.getList { items ->
            list.value = items
            listLoading.set(false)
        }
    }
Run Code Online (Sandbox Code Playgroud)

缺点:这种方法有任何缺点吗?

第二种方法:

  1. ViewModel 提供 LiveData
  2. Activity …

android design-patterns android-databinding android-mvvm android-architecture-components

4
推荐指数
1
解决办法
2868
查看次数

如何在ViewModel中注入SharedPreferences?

我正在开发一种使用MVVM方法的Android应用程序,我需要访问ViewModel中的SharedPreferences,但是我不知道该怎么做。

我知道可以访问从AndroidViewModel继承的类的上下文,但是我想知道如果可能的话,如何通过注入来实现。

为此,我使用的是Dagger 2。

谢谢

android dagger-2 android-mvvm

4
推荐指数
1
解决办法
2005
查看次数

Android:将 FCM 通知保存到 Room DB

我正在使用 firebase FCM 来获取通知。我想要如果收到通知,它应该存储在我的 RoomDatabase 中。稍后,当用户打开应用程序时,将在通知部分显示所有通知

我正在使用 MVVM,我试图通过ViewModel进行保存,但它不起作用。这是我目前的代码。

public class MessagingService extends FirebaseMessagingService {

    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        Log.d("MessagingService", s);
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        // Check if message contains a notification payload.

        if (remoteMessage.getData().isEmpty()){
            showNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
        } else {
            showNotification(remoteMessage.getData());
        }

    }

    private void showNotification(Map<String, String> data) {


        Bitmap bitmap;

        String title = data.get("title").toString();
        String body = data.get("body").toString();
        String imageUri = data.get("image").toString();
        String TrueOrFalse = data.get("AnotherActivity").toString();

        bitmap = getBitmapfromUrl(imageUri); …
Run Code Online (Sandbox Code Playgroud)

android android-sqlite firebase-cloud-messaging android-mvvm android-room

4
推荐指数
1
解决办法
2936
查看次数

使用 SavedStateHandle 加入 sharedViewModel

我有单个活动应用程序和片段数量。其中一些片段正在使用我的视图模型,通常是这样的:

private val myViewModel: MyViewModel by sharedViewModel()
Run Code Online (Sandbox Code Playgroud)

如果我想同时拥有模型shared并使用 SavedStateHandle 保持其状态怎么办?我无法弄清楚这是否受支持,如果是,则需要如何使用它(在托管活动中将 viewmodel 声明为 stateViewModel 不起作用)。

android android-mvvm android-viewmodel koin androidx

4
推荐指数
1
解决办法
1959
查看次数

Dispatcher.IO 和 Dispatcher.Main 哪个更适合用于 API 调用?

我在 Android 应用程序中使用 MVVM 架构模式。我想从我的 using 进行 API 调用我ViewModel需要coroutinescope.lauch{}指定 Dispatcher 因为Dispatcher.IO它将在 IO 线程中执行,还是只使用由 提供的 Dispatcher ViewModelDispatcher.Main

android kotlin android-mvvm android-viewmodel kotlin-coroutines

4
推荐指数
1
解决办法
937
查看次数

Android:MVVM是否可以从ViewModel显示消息(吐司/小吃店等)

我想知道从ViewModel在视图中显示某种消息的最佳方法是什么。我的ViewModel正在进行POST调用,“ onResult”我想向包含特定消息的用户弹出一条消息。

这是我的ViewModel:

public class RegisterViewModel extends ViewModel implements Observable {
.
.   
.
public void registerUser(PostUserRegDao postUserRegDao) {

    repository.executeRegistration(postUserRegDao).enqueue(new Callback<RegistratedUserDTO>() {
        @Override
        public void onResponse(Call<RegistratedUserDTO> call, Response<RegistratedUserDTO> response) {
            RegistratedUserDTO registratedUserDTO = response.body();
            /// here I want to set the message and send it to the Activity

            if (registratedUserDTO.getRegisterUserResultDTO().getError() != null) {

            }
        }

    });
}
Run Code Online (Sandbox Code Playgroud)

我的活动:

public class RegisterActivity extends BaseActivity {   

@Override
protected int layoutRes() {
    return R.layout.activity_register;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    AndroidInjection.inject(this);
    super.onCreate(savedInstanceState); …
Run Code Online (Sandbox Code Playgroud)

android-toast android-snackbar android-mvvm

3
推荐指数
2
解决办法
3316
查看次数

java.lang.ClassCastException:com.eng.bt_eng_mobility.viewmodel.HomeViewModelFactory 无法转换为 androidx.lifecycle.ViewModel

我收到这个错误。我在同一个 ViewModel 类文件中创建了 ViewModelFactory 类。当我尝试初始化视图模型时,出现此错误。

//Code written in fragment class in onCreateView after binding code//
homeViewModelFactory = HomeViewModelFactory((requireActivity().application as Application).repository)
        homeViewModel = ViewModelProvider(this, homeViewModelFactory)
                .get(HomeViewModel::class.java)


//Viewmodelfactoryclass//
class HomeViewModelFactory(private val homeRepository: HomeRepository) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(HomeViewModel::class.java)) {
            return HomeViewModelFactory(homeRepository) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}


Run Code Online (Sandbox Code Playgroud)

android repository kotlin android-mvvm android-viewmodel

3
推荐指数
1
解决办法
1861
查看次数

安卓。如何使用干净架构的分页?

我正在使用MVVM干净的架构编写应用程序。在其中一个屏幕上,我需要使用 来RecyclerView实现pagination。我要使用图书馆Paging3

Android 开发者建议在存储库层使用PagingSource和。RemoteMediator但同时,在许多来源中,我读到数据层和领域层不应该了解有关android框架的任何信息。

但现在我必须在数据层的数据源中使用android库。这在 a 的上下文中正确吗clean architecture

请帮我弄清楚,我不明白如何使用干净的架构实现分页。

android android-recyclerview clean-architecture android-mvvm android-paging-3

3
推荐指数
1
解决办法
1475
查看次数

Android 我的底部应用程序的一个栏与我的回收视图重叠

我正在尝试解决我的回收器视图与底部应用栏重叠的问题。这是我的布局代码。

<androidx.coordinatorlayout.widget.CoordinatorLayout
    android:id="@+id/notes_container_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
     >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="40dp"
            android:padding="8dp"
            android:text="@string/myTasksHeader"
            android:textColor="@color/appBarTextColor"
            android:textSize="40dp" />

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/recyclerview"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:clipToPadding="false"
                android:padding="16dp"
                android:scrollbars="none"
                tools:listitem="@layout/note_list_item" />
        </ScrollView>

    </LinearLayout>

    <com.google.android.material.bottomappbar.BottomAppBar
        android:id="@+id/bottomAppBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:backgroundTint="@color/colorPrimary"
        app:hideOnScroll="false"
        app:menu="@menu/appbar_menu"
        app:navigationIcon="@drawable/ic_menu" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/add_note_fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/medium_margin"
        android:backgroundTint="@color/colorPrimary"
        app:layout_anchor="@id/bottomAppBar"
        app:srcCompat="@drawable/ic_add_black_24dp"
        tools:ignore="VectorDrawableCompat" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>
Run Code Online (Sandbox Code Playgroud)

当我填写列表时,我无法到达回收器视图中的最后一个项目。我尝试添加保证金,但没有成功。

在此输入图像描述

android android-layout android-fragments kotlin android-mvvm

2
推荐指数
1
解决办法
1255
查看次数