首页 > 解决方案 > 除了 ViewModel,片段和 Activity 之间的通用上下文相关代码在哪里保留?

问题描述

我正在创建这个新的 android 应用程序,但我陷入了这个思考过程。我有一个底部工作表的活动,您可以在其中选择从图库或相机中选择图像以将附件添加到帖子中。所以我需要请求权限,监听权限回调,解析图库/相机结果并切换 UI,这是很多代码。问题是我有一个片段可以做完全相同的事情来上传个人资料图片。如果是两个活动,我可以将代码添加到 baseActivity。但它是一个片段和一个活动。另一方面,你也不应该让你的 ViewModel 膨胀,这两个组件是完全独立的。

我曾想过将其放入 ViewModel 中,但无法将视图放入其中。另外,我不知何故知道这个要求是一个普遍的要求。我知道演示者模式,但您仍然不能将视图放入其中。

// starting gallery
private fun startGallery(type: String, title: String, requestCode: Int){
    val intent = Intent()
    intent.type = type
    intent.action = Intent.ACTION_PICK
    startActivityForResult(Intent.createChooser(intent, title), 
    requestCode)
}

// starting camera intent
private fun startCameraFor(action: String, requestCode: Int) {
    val takeVideoIntent = Intent(action)
    if (takeVideoIntent.resolveActivity(context?.packageManager) != null) 
{
        startActivityForResult(takeVideoIntent, requestCode)
    }
}

 // Handling image results
 override fun onActivityResult(requestCode: Int, resultCode: Int, data: 
 Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if(resultCode == Activity.RESULT_OK) {
        postViewModel.uploadImageResults(data = data, requestCode = 
        requestCode, userId = "c7c2352b-5449-43bf-a099-688843025130")
    }
    toggleBottomSheet()
}

  // Check for permission
  private fun permissionAction(permission: String =  
  Manifest.permission.READ_EXTERNAL_STORAGE, callback: () -> Unit){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        val checkPermission = ContextCompat.checkSelfPermission(context!!, 
        permission)
        if (checkPermission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity!!, 
            arrayOf(permission), Constants.REQUEST_CODE_STORAGE_PICK)
        } else {
            callback()
        }
    }
}

// Toggles bottom sheet
private fun toggleBottomSheet() {
    if(bottomSheet.state == BottomSheetBehavior.STATE_COLLAPSED) {
        bottomSheet.state = BottomSheetBehavior.STATE_EXPANDED
    } else {
        bottomSheet.state = BottomSheetBehavior.STATE_COLLAPSED
    }
}

标签: androidoopmvvmkotlinmvp

解决方案


推荐阅读