2
3

ZXingをJetpack Composeで利用する

Posted at

AndroidのXMLレイアウトをJetpack Composeに移行していて、QRコードリーダーのライブラリであるzxing-android-embeddedを使っている部分を移行することがありました。
しかしJetpack Composeで使っている情報が少なかったので備忘として簡単に残しておきます。

実装

Zxing.kt
@Composable
fun AdminClubMembershipScanScreen(navController: NavHostController) {
    val context = LocalContext.current
    val lifecycleOwner = LocalLifecycleOwner.current

    val compoundBarcodeView = remember {
        CompoundBarcodeView(context).apply {
            val capture = CaptureManager(context as Activity, this)
            capture.initializeFromIntent(context.intent, null)
            this.setStatusText("")
            capture.decode()
            // 読み取り枠部分のサイズ設定
            barcodeView.fromingRectSize = Size(300, 300)
            // 中央に表示される赤線を消す
            this.viewFinder.setLaserVisibility(false)
            // 枠外の背景の色を変更
            this.viewFinder.setMaskColor(color.zxing_viewfinder_mask)
            barcodeView.decodeContinuous(
                object : BarcodeCallback {
                    override fun barcodeResult(result: BarcodeResult?) {
                        // 読み取り成功した時の処理などを書く
                    }
                }
            )
        }
    }

    DisposableEffect(lifecycleOwner) {
        compoundView.resume()
        onDispose {
            // 読み取りストップ
            compoundBarcodeView.pause()
            compoundBarcodeView.barcodeView.stopDecoding()
        }
    }

    AndroidView(
        modifier = Modifier,
        factory = {
            compoundBarcodeView 
        },
    )
}

何かしらカスタムしたい場合は、とりあえずCompoundBarcodeViewを作ってそこから内部構造を追っていけば見つかると思います。
まあ今はGoogle Code Scanner APIML Kitを使う方が主流なのでしょうかねー

参考

Stack Overflow

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3