AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
다음 내용을 추가한다.
SingleLiveEvent에 대한 내용은
https://velog.io/@dustndus8/%EC%95%88%EB%93%9C%EB%A1%9C%EC%9D%B4%EB%93%9CAndroid-MVVM-%EC%9D%B4%EB%B2%A4%ED%8A%B8-%EC%B2%98%EB%A6%AC-ovw9fsa1
참조
ExampleViewModel.kt
class RegisterEventsViewModel : ViewModel() {
val startGalleryClickEvent = SingleLiveEvent<Any>()
fun onImageButtonClick() {
startGalleryClickEvent.call()
}
}
activity_example.xml
<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
<variable
name="registerViewModel"
type="org.inu.events.viewmodel.RegisterEventsViewModel" />
</data>
...
<ImageButton
android:id="@+id/imageButton_postImage"
android:layout_width="56dp"
android:layout_height="56dp"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:background="@drawable/img_btn_background"
android:onClick="@{ () -> registerViewModel.onImageButtonClick()}"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView_postImage" />
onnClick에
android:onClick="@{ () -> registerViewModel.onImageButtonClick()}"
다음과 같이 작성해준다.
class RegisterEventsActivity : AppCompatActivity() {
private val PERMISSION_ALBUM = 101
private val REQUEST_STORAGE = 1000
private lateinit var registerModel: RegisterEventsViewModel
private lateinit var binding: RegisterEventsBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.register_events)
registerModel = RegisterEventsViewModel()
binding.registerViewModel = registerModel
binding.lifecycleOwner = this
initAddPhotoButton()
}
private fun initAddPhotoButton() {
registerModel.startGalleryClickEvent.observe(this, {
Log.i("BUTTON", "initAdd")
when {
ContextCompat.checkSelfPermission(
this,
android.Manifest.permission.READ_EXTERNAL_STORAGE
) == PackageManager.PERMISSION_GRANTED -> {
navigatePhotos()
Log.i("BUTTON", "navigate")
}
shouldShowRequestPermissionRationale(android.Manifest.permission.READ_EXTERNAL_STORAGE) -> {
showPermissionContextPopup()
Log.i("BUTTON", "showpermission")
}
else -> {
requestPermissions(
arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE),
REQUEST_STORAGE
)
Log.i("BUTTON", "else")
}
}
}
)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode != Activity.RESULT_OK) {
return
}
when (requestCode) {
REQUEST_STORAGE -> {
val selectedImageUri: Uri? = data?.data
if (selectedImageUri != null) {
selectedImageUri?.let { uri ->
//imageview.setImageURI(uri)
}
} else {
Toast.makeText(this, "사진을 가져오지 못했습니다.", Toast.LENGTH_SHORT).show()
}
}
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
REQUEST_STORAGE -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// todo 권한이 부여된 것입니다.
navigatePhotos()
} else {
Toast.makeText(this, "권한을 거부하였습니다.", Toast.LENGTH_SHORT).show()
}
}
else -> {
}
}
}
private fun navigatePhotos() {
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "image/*"
startActivityForResult(intent, REQUEST_STORAGE)
}
private fun showPermissionContextPopup() {
AlertDialog.Builder(this)
.setTitle("권한이 필요합니다.")
.setMessage("앱에서 사진을 불러오기 위해 권한이 필요합니다.")
.setPositiveButton("동의") { _, _ ->
requestPermissions(
arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE),
PERMISSION_ALBUM
)
}
.setNegativeButton("취소") { _, _ -> }
.create()
.show()
}
}
기록용으로 작성되었음
참고한 코드