Android (안드로이드)
Android in A..Z - QR Code
강태종
2021. 3. 16. 16:41
QR Code
QR Code란 흑백으로 이루어진 Matrix에 정보를 포함한 코드이다.
zxing-android-embedded 라이브러리를 사용하여 Android에서 쉽게 QR Code를 읽고 만들 수 있다.
Dependency
dependencies {
// QR
implementation 'com.journeyapps:zxing-android-embedded:3.6.0'
}
Generate
한국어를 지원하기 위해 ISO 8859-1코드를 사용하여 포맷팅한다.
object BindingAdapter {
@JvmStatic
@BindingAdapter("qrCode")
fun setQRCode(view: ImageView, qrCode: String?) {
if (qrCode == null) {
view.setImageBitmap(null)
return
}
val barcodeEncoder = BarcodeEncoder()
val bitmap = barcodeEncoder.encodeBitmap(qrCode.toByteArray().toString(Charsets.ISO_8859_1), BarcodeFormat.QR_CODE, 400, 400)
view.setImageBitmap(bitmap)
}
}
Scan
IntentIntegrator을 통해 Scan을 하고 Scan받은 결과를 onActivityResult로 받아온다.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
IntentIntegrator.forSupportFragment(this).initiateScan()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
val qrCode = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
if (qrCode != null) {
if (qrCode.contents == null) {
// Toast.makeText(requireContext(), "Cancelled", Toast.LENGTH_LONG).show()
} else {
findNavController().previousBackStackEntry?.savedStateHandle?.set("QR CODE", qrCode.contents)
}
} else {
super.onActivityResult(requestCode, resultCode, data)
}
findNavController().navigateUp()
}
Copy
ClipboardManager를 통해 QR Code나 TextView를 클릭시 복사하도록 하였습니다.
private fun initOnClick() {
binding.setOnClick {
(requireContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager).apply {
setPrimaryClip(ClipData.newPlainText("QRCode", binding.qrCode))
}
Toast.makeText(requireContext(), "Copy : ${binding.qrCode}", Toast.LENGTH_SHORT).show()
}
}
Git (예제코드)
github.com/KangTaeJong98/Example/tree/main/Android/QRCode
KangTaeJong98/Example
My Example Code. Contribute to KangTaeJong98/Example development by creating an account on GitHub.
github.com