最近在学习如何使用
Jetpack以及kotlin,相较于以往使用的onActivityResult,androidx-activity 1.2.0-alpha02及Fragment 1.3.0-alpha02版本中新追加了apiActivityResultContract
环境配置
为使用ActivityResultContract,我们需要在gradle文件中添加相关依赖,这里我使用的是alpha03版本
implementation "androidx.activity:activity-ktx:1.2.0-alpha03"
implementation 'androidx.fragment:fragment-ktx:1.3.0-alpha03'
使用方法
ActivityResultContract和Fragment可以通过registerForActivityResult()函数创建launcher,接着通过调用launcher.launch(intent)进行使用
由于版本或其他不可抗力,我在使用过程中发现registerForActivityResult()不可使用,查阅资料发现,registerForActivityResult()是prepareCall()的重命名,于是只能暂时使用prepareCall()
读取图片
设置launcher
private val launcher = prepareCall(ActivityResultContracts.GetContent()) { uri ->
Toast.makeText(context,"uri:$uri",Toast.LENGTH_SHORT).show()
}
launcher调用launch
launcher.launch("image/*")
权限获取(RequestPermission)
前提
如需动态获取对应权限,应当在AndroidManifest下对应填写相应语句,如WRITE_EXTERNAL_STORAGE
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
设置launcher
val requestPermissionLauncher =
prepareCall(
ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
if (isGranted) {
Toast.makeText(context, "result: granted", Toast.LENGTH_LONG).show()
} else {
Toast.makeText(context, "result:fail", Toast.LENGTH_LONG).show()
}
}
launcher调用launch
requestPermissionLauncher.launch(WRITE_EXTERNAL_STORAGE)
总结
老菜鸡了,看个jetpack的权限调用看了一个下午,写个文章记录一下踩过的坑吧,确实使用jetpack会让代码整洁许多,好东西好东西,继续加油