I am beginner to android studio and just started learning Kotlin. I have a problem: I cannot add a picture from the camera or from the gallery to the ImageView in a fragment. Help me please:( I've seen examples with bitmap, but it doesn't work for Activity and Fragment. I inserted onActivityResult, but the photo from the camera did not appear in the imageView. I do not understand how to correctly link to the imageView. P.S. Sorry for my bad English:)
HomeFragment.kt
package com.example.avtoinspector111.ui.home
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.avtoinspector111.R
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
const val Image_Capture_Code = 24
const val REQUEST_CODE=24
const val REQUEST_TAKE_PHOTO=24
class HomeFragment : Fragment() {
lateinit var imageView: ImageView
lateinit var button: Button
private val pickImage = 100
private var imageUri: Uri? = null
private lateinit var homeViewModel: HomeViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
homeViewModel =
ViewModelProvider(this).get(HomeViewModel::class.java)
val root = inflater.inflate(R.layout.fragment_home, container, false)
//val textView: TextView = root.findViewById(R.id.text_home)
// homeViewModel.text.observe(viewLifecycleOwner, Observer {
// textView.text = it
// })
// вызов галереи
val btn1: Button = root.findViewById(R.id.buttongallery)
btn1.setOnClickListener {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, REQUEST_CODE)
}
// вызов камеры
var btn: Button = root.findViewById(R.id.buttoncamera)
btn.setOnClickListener {
val bInt = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(bInt, REQUEST_CODE)
}
return root
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode== REQUEST_CODE && requestCode == Activity.RESULT_OK){
val image=data?.extras?.get("data") as Bitmap
imageView.setImageBitmap(image)
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
}
question from:https://stackoverflow.com/questions/66047755/adding-in-imageview-from-camera-gallery-in-fragment-android-sudio-kotlin