바코드 스캔 라이브러리 중에 zxing 라이브러리가 있다.
자세한 내용은 아래 참조
https://github.com/journeyapps/zxing-android-embedded#custom-layout
GitHub - journeyapps/zxing-android-embedded: Barcode scanner library for Android, based on the ZXing decoder
Barcode scanner library for Android, based on the ZXing decoder - GitHub - journeyapps/zxing-android-embedded: Barcode scanner library for Android, based on the ZXing decoder
github.com
해당 라이브러리를 이용하여 바코드 스캔을 하는 앱을 만들어보도록 하겠다.
바코드를 인식하기 위해서는 카메라를 사용해야 하기 때문에 Camera 권한을 획득해주어야 한다.
AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA" />
그 다음에는 zxing 라이브러리를 사용하기 위해 해당 라이브러리를 implementation 해주어야 한다.
implementation 'com.journeyapps:zxing-android-embedded:4.3.0'
그 다음에는 사용하고자하는 레이아웃 파일에 스캐너 뷰를 넣어야 한다.
<com.journeyapps.barcodescanner.DecoratedBarcodeView
android:visibility="gone"
android:id="@+id/qr_scanner"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
나는 버튼을 누르면 스캐너를 실행하고 한번더 누르면 종료하기 위해 두개의 플로팅 버튼을 추가하였다.
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:visibility="gone"
android:id="@+id/fab3"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
그 다음 스캐너에 관한 코드를 작성해주겠다.
binding.qrScanner.apply {
setStatusText("")
decodeContinuous { result ->
Toast.makeText(this@MainActivity, result.toString(), Toast.LENGTH_SHORT).show()
pause()
}
pause()
}
정상적으로 스캔이 완료되면,
Toast를 이용하여 result를 출력해주고, pause()를 하는 이유는 스캔을 하고 난 후 또 바로 스캔해버리기 때문에 pause()를 추가하였다.
그 다음에 플로팅 버튼에도 클릭 했을 때 이벤트를 추가해주었다.
binding.fab2.setOnClickListener {
binding.qrScanner.resume()
binding.qrScanner.visibility = View.VISIBLE
binding.fab3.visibility = View.VISIBLE
}
binding.fab3.setOnClickListener {
binding.qrScanner.pause()
binding.qrScanner.visibility = View.GONE
binding.fab3.visibility = View.GONE
}
이렇게 하면, 눌렀을 때 스캐너가 화면에 나타난다, 그리고 다시 누르면 스캐너가 닫히는 기능을 구현할 수 있다.
사실은 스캐너를 엑테비티로 따로 두어서 만들면 더 편하긴 하다.
'안드로이드' 카테고리의 다른 글
Retrofit에서 Interceptor와 Converter란 (0) | 2023.10.06 |
---|---|
[Android] await()이 안될 때 (0) | 2023.09.01 |
[Kotlin] 화면 캡쳐 기능 구현하기 (with Hilt, MVVM) (0) | 2023.08.27 |
[Android] Hilt - Retrofit + ViewModel로 이해해보기 (0) | 2023.08.25 |
[Android] floating button Icon 색상 적용 안되는 문제 (0) | 2023.08.25 |