我应该在 fragment/activity 还是视图模型中编写此代码?

should I write this code in my fragment/activity or in my viewmodel?

我是 Android MVVM 的新手,所以我需要执行图像裁剪并请求访问图片库的权限,我很困惑这些应该在我的片段中还是在我的视图模型中执行。

开始裁剪 activity 保存在设备上的预先获取的图像我使用此代码

    CropImage.activity(selectedImagePosterFromGalleryUri)
        .setGuidelines(CropImageView.Guidelines.ON)
        .setRequestedSize(posterMaxWidthSize, posterMaxHeightSize, CropImageView.RequestSizeOptions.RESIZE_INSIDE)
        .start(mContext, this)

requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE

时,可以在我的片段中的 onActivityResult 中访问此代码的结果(裁剪图像)

如果它被视为用户输入,我会感到困惑,所以我可以将此代码放入我的片段中,或者它被视为逻辑/过程,因此应该放在 viewmodel 中?

而且我还需要请求访问图库的权限,请求权限我使用一个库,代码将是这样的。我必须放入片段或视图模型吗?

    @AfterPermissionGranted(PERMISSION_READ_EXTERNAL_STORAGE)
    private fun checkPermission() {


        if (EasyPermissions.hasPermissions(mContext, Manifest.permission.READ_EXTERNAL_STORAGE)) {


            chooseImageFromGallery()

        } else {

            EasyPermissions.requestPermissions(
                this,
                "we need your permission to access your gallery",
                PERMISSION_READ_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE)
        }



    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {

        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {

            // showing app setting, so the user eventually can switch the permission manually in the setting section
            AppSettingsDialog.Builder(this).build().show()
        }

    }

    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {


    }

让我感到困惑的是这里的这句话https://developer.android.com/jetpack/docs/guide,据说:

It's a common mistake to write all your code in an Activity or a Fragment. These UI-based classes should only contain logic that handles UI and operating system interactions.

我很困惑裁剪图像和访问图库是否被视为句柄 UI 和操作系统交互的逻辑

我不太明白选择一个代码应该在viewmodel还是在view(fragment/activity)。对于业务逻辑,很明显应该在视图模型中,但是像这样的代码呢?请帮忙

您应该将它放在您的 ViewModel 中并传递函数所需的必要参数。

为了能够选择放置这些逻辑的位置,请考虑更改 UI。一个例子是为 TextView 分配文本的方法可以在 Fragment/Activity 级别完成,但调用它的是 ViewModel。

据 google 人说,

ViewModels shouldn’t know anything about Android. This improves testability, leak safety and modularity. A general rule of thumb is to make sure there are no android.* imports in your ViewModels (with exceptions like android.arch.*). The same applies to presenters.

如果你的裁剪操作满足这个条件,那么肯定会把它扔到 ViewModel.

了解更多详情 https://medium.com/androiddevelopers/viewmodels-and-livedata-patterns-antipatterns-21efaef74a54