我有简单的任务。在recyclerView当我点击任何按钮,我想启动相机,拍照,然后捕捉这张照片。但是我找不到任何解决办法。我在RecyclerAdapter中尝试了什么。kt:
inner class ViewHolder(itemView: View):RecyclerView.ViewHolder(itemView) {
var textView1: TextView = itemView.findViewById(R.id.firma_textView1)
init {
textView1.setOnClickListener {
capturePhoto(context, activity)
}
}
}
fun capturePhoto(context: Context, activity: Activity) {
if (getCameraPermission(context)) {
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(activity, cameraIntent, FirstFragment.CAMERA_REQUEST_CODE, null)
} else {
ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.CAMERA), FirstFragment.CAMERA_REQUEST_CODE)
}
}
private fun getCameraPermission (context: Context):Boolean {
return ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
}
有了这个代码,我可以启动相机,拍照,但在RecyclerAdapter中没有办法捕捉拍摄的图像。
在Fragment中捕获图像的正常方法是这样的:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
var buttonCapturePhoto = view.findViewById<Button>(R.id.button)
buttonCapturePhoto.setOnClickListener {
capturePhoto()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == CAMERA_REQUEST_CODE) {
print("photo captured")
}
}
private fun capturePhoto() {
if (getCameraPermission(requireContext())) {
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE)
} else {
ActivityCompat.requestPermissions(requireActivity(), arrayOf(Manifest.permission.CAMERA), CAMERA_REQUEST_CODE)
}
}
private fun getCameraPermission (context: Context):Boolean {
return ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
}
我也在Android开发者页面找到了这篇文章-https://developer.android.com/training/basics/intents/result
他们建议创建类MyLifecycleObserver并在Fragment中使用它,但我无法在RecycleAdapter中使用此代码
lateinit var observer : MyLifecycleObserver
override fun onCreate(savedInstanceState: Bundle?) {
// ...
observer = MyLifecycleObserver(requireActivity().activityResultRegistry)
lifecycle.addObserver(observer)
}
我在activityResultRegistry
和lifecycle
处出错
我还创建了一个用于测试的git仓库:https://github.com/Katzzer/recyclerViewPhotoCaptureKotlinAndroid
1条答案
按热度按时间krcsximq1#
你应该把你的click事件传递给fragment/activity
1.在适配器中创建自定义
interface
1.将其传递到适配器构造函数中
1.已在
Fragment/Activity
中初始化适配器1.收听
Fragment/Activity
中的点击事件1.在
Fragment\Activity
中创建capturePhoto
函数