<string name="upload_image">이미지 업로드</string>
<string name="delete_image">이미지 삭제</string>
Select a single media item
val pickMedia = registerForActivityResult(PickVisualMedia()) { uri -> if (uri != null) { Log.d("PhotoPicker", "Selected URI: $uri") } else { Log.d("PhotoPicker", "No media selected") } } // Launch the photo picker and let the user choose images and videos. pickMedia.launch(PickVisualMediaRequest(PickVisualMedia.ImageAndVideo)) // Launch the photo picker and let the user choose only images. pickMedia.launch(PickVisualMediaRequest(PickVisualMedia.ImageOnly)) // Launch the photo picker and let the user choose only videos. pickMedia.launch(PickVisualMediaRequest(PickVisualMedia.VideoOnly))
class HomeActivity : AppCompatActivity() {
private val TAG = "HomeActivity"
private val homeImageView:ImageView by lazy{findViewById(R.id.iv_home)}
private val imageButton:Button by lazy{findViewById(R.id.btn_image)}
...
private var isImageUploaded = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
setHomeImageViewRandom()
val pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
if (uri != null) {
Log.d(TAG, "Photo Picker) Selected URI: $uri")
setHomeImageView(uri)
setImageButtonUpload(false)
} else {
Log.d(TAG, "Photo Picker) No media selected")
}
}
imageButton.setOnClickListener {
if(!isImageUploaded){
pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
}
else{
setHomeImageViewRandom()
setImageButtonUpload(true)
}
}
...
}
private fun setHomeImageViewRandom(){
val imageNumber:Int = Random.nextInt(5)+1
val imageId = resources.getIdentifier("ham${imageNumber}", "drawable", packageName)
homeImageView.setImageResource(imageId)
}
private fun setHomeImageView(uri:Uri){
homeImageView.setImageURI(uri)
}
private fun setImageButtonUpload(flag:Boolean){
if(flag) {
isImageUploaded = false
imageButton.text = getString(R.string.upload_image)
}
else{
isImageUploaded = true
imageButton.text = getString(R.string.delete_image)
}
}
}