kotlin代码实现如下 功能,一个imageview点击后,弹出选择框,里面有选择图片和拍摄图片以及取消 按钮
时间: 2024-09-29 21:10:16 浏览: 67
在Kotlin中,你可以使用Android的`ACTION_PICK`和`ACTION_IMAGE_CAPTURE`系统动作结合`DialogFragment`或`AlertDialog`来实现这样的功能。这里是一个简单的例子:
首先,确保你已经添加了CameraX库(如果需要拍照功能):
```kotlin
dependencies {
implementation "androidx.camera:camera-core:1.0.0-alpha19"
// 其他依赖...
}
```
然后创建一个`PickAndCaptureFragment`:
```kotlin
class PickAndCaptureFragment : DialogFragment(), View.OnClickListener {
private lateinit var imageView: ImageView
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.dialog_pick_and_capture, container, false)
imageView = view.findViewById(R.id.imageView)
// 给imageView设置点击监听
imageView.setOnClickListener(this)
return view
}
override fun onClick(view: View) {
val dialogBuilder = AlertDialog.Builder(requireContext())
// 图片选择
val galleryIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
dialogBuilder.setTitle("选择图片")
dialogBuilder.setItems(arrayOf(R.string.choose_image, R.string.cancel), { _, index ->
when (index) {
0 -> startActivityForResult(galleryIntent, REQUEST_IMAGE_PICK)
else -> dismiss()
}
})
// 拍照
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
dialogBuilder.setTitle("拍摄照片")
dialogBuilder.setPositiveButton("拍照") { _, _ ->
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE)
}
dialogBuilder.setNegativeButton("取消", { _, _ -> dismiss() })
dialogBuilder.show()
}
// 这里需要处理请求结果,区分是从Gallery还是相机获取的图片
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_IMAGE_PICK && resultCode == RESULT_OK) {
val imageUri = data?.data
handleImage选Path(imageUri)
} else if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
val imageBitmap = CropImage.getBitmapFromResult(data)
handleImageBitmap(imageBitmap)
}
}
// 根据实际需求实现handleImage和handleImageBitmap方法
private fun handleImage(imageUri: Uri)? { ... }
private fun handleImageBitmap(bitmap: Bitmap)? { ... }
companion object {
const val REQUEST_IMAGE_PICK = 1
const val REQUEST_IMAGE_CAPTURE = 2
}
}
```
在布局文件dialog_pick_and_capture.xml中,你需要包含一个ImageView和对应的按钮:
```xml
<LinearLayout>
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<!-- 添加其他按钮 -->
</LinearLayout>
```
别忘了在主Activity中管理Fragment,并且在对应的回调中显示这个对话框:
```kotlin
val fragment = PickAndCaptureFragment()
fragment.show(supportFragmentManager, "pickAndCaptureFragment")
```
阅读全文