android - 除了 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
}
}
解决方案
推荐阅读
- wordpress - Wordpress / 站点运行状况 / REST API 错误 / 环回错误
- javascript - 在android中使用javascript获取web源的最快方法
- linux - 使用 awk 计算来自另一个文件的模式的出现次数
- c# - C# Json 解析 - 对象数组和访问数组
- amazon-web-services - Getting Serverless Deployment bucket error when using serverless-deployment-bucket plugin
- rust - How to look up values in a HashMap
- reactjs - how to check if input is clear (react redux)
- python - How to detect trafic light color with histogram info using OpenCV?
- laravel - ErrorException chdir(): No such file or directory (errno 2) when trying to create a laravel project
- node.js - socket.io:io.origins 不是函数