기능 설명
✔ 카메라를 찍거나 갤러리에서 사진을 불러와서 선택한 사진을 이미지뷰로 띄워주는 코드
UI
전체 코드
AndroidManifest.xml
더보기
1
2
3
4
5
6
7
8
9
10
11
|
<application
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.chooserintent.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>
|
cs |
xml/file_paths.xml
더보기
1
2
3
4
5
6
|
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images"
path="Android/data/com.example.chooserintent/files/Pictures" />
</paths>
|
cs |
MainActivity.kt
더보기
class MainActivity : AppCompatActivity() {
val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
private lateinit var photoPath: String
private val Intent_CODE = 1
private val PERMISSION_CODE = 2
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
}
fun onClick(v: View) {
when(v.id) {
R.id.button -> {
if (!allPermissionsGranted()) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE), PERMISSION_CODE)
}
chooserIntent()
}
}
}
private fun chooserIntent() {
// 갤러리에서 불러오기 Intent
val galleryIntent = Intent(Intent.ACTION_PICK)
galleryIntent.type = "image/*"
// 다중 Intent 선택 창 띄우기
val chooserIntent = Intent.createChooser(galleryIntent,"")
// 카메라로 사진 찍기 Intent
Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { captureIntent ->
if (captureIntent.resolveActivity(this.packageManager) != null) {
val photoFile: File? =
try {
createImageFile() // 파일 생성
} catch (ex: IOException) {
null
}
photoFile?.also { file ->
val photoURI: Uri = FileProvider.getUriForFile(
this, "com.example.chooserintent.fileprovider", file
)
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
}
// 다중 Intent 선택 창에 카메라로 사진찍기 추가
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, arrayOf(captureIntent))
}
}
startActivityForResult(chooserIntent, Intent_CODE) // 다중 Intent 선택 창 실행
}
@Throws(IOException::class)
private fun createImageFile(): File {
// Create an image file name
val timeStamp: String = SimpleDateFormat("yyyy-MM-dd_HH_mm_ss").format(Date())
val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File.createTempFile (
"JPEG_${timeStamp}_",
".jpg",
storageDir
).also { file ->
photoPath = file.absolutePath
}
}
private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all {
ContextCompat.checkSelfPermission(
baseContext, it) == PackageManager.PERMISSION_GRANTED
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
Intent_CODE -> {
// 갤러리에서 찍은 사진 띄워주기
data?.data?.let { uri ->
binding.imageView.setImageURI(uri)
}
// 카메라로 찍은 사진 띄워주기
val file = File(photoPath)
val selectedUri = Uri.fromFile(file)
try {
selectedUri?.let {
val decode = ImageDecoder.createSource(this.contentResolver, selectedUri)
val bitmap = ImageDecoder.decodeBitmap(decode)
binding.imageView.setImageBitmap(bitmap)
}
} catch (e: java.lang.Exception){
e.printStackTrace()
}
}
}
}
companion object {
private val REQUIRED_PERMISSIONS = arrayOf(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
}
}
activity_main.xml
더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@+id/imageView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:text="Intent"
android:onClick="onClick" />
<ImageView
android:id="@+id/imageView"
android:layout_width="300dp"
android:layout_height="300dp"
app:layout_constraintTop_toBottomOf="@+id/button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
|
cs |
'Android > Code' 카테고리의 다른 글
[Project] [Android] [Kotlin] Log Window (0) | 2021.10.18 |
---|---|
[Android] [Kotlin] Google Map (0) | 2021.09.24 |
[Android] [Kotlin] EditText 자동 포커싱 및 키보드 (0) | 2021.09.23 |
[Android] [Kotlin] Dialog로 액티비티 띄우기 (0) | 2021.09.15 |
[Android] [Kotlin] 프래그먼트 사용 방법 및 구조 (0) | 2021.09.11 |