使用ツール
Android Studio Flamingo | 2022.2.1 Patch 2
1. 通常のプロジェクトを作成
2D グラフィックを表示するので、アクティビティを含むプロジェクトを作成する。
「Empty Activity」「Empty Views Activity」等のプロジェクトが対象。
「No Activity」でも構わないが、Default Activity の追加が必要になるので、ここでは割愛する。(選択しない)
2. 依存モジュールの用意
2-1. 環境設定ファイルに QR コード生成モジュールを使用する宣言を記述する。
2-2. 設定を反映させる。
要素名 内容 備考 ファイル Android > Gradle > build.gradle (app) - モジュール com.journeyapps:zxing-android-embedded:4.3.0 QRCodeWriter, BitMatrix, BarcodeEncoder 等を利用可能
(4.3.0 は本稿記述時の最新版)
build.gradle (app)
Kotlin (build.gradle.kts) の場合は implementation("com.journeyapps:zxing-android-embedded:4.3.0") を記述する。
dependencies { implementation 'androidx.appcompat:appcompat:1.6.1' implementation 'com.google.android.material:material:1.5.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.4' implementation 'androidx.navigation:navigation-fragment:2.5.2' implementation 'androidx.navigation:navigation-ui:2.5.2' implementation 'com.journeyapps:zxing-android-embedded:4.3.0' testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test.ext:junit:1.2.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.6.1' }
File > Sync Project with Gradle Files を実行する。
3. ImageView を設置
Activity に QR コードを表示するための ImageView を設置する。
部品種別 ID 備考 ImageView ivQrCode 下記プログラムコードからこの ID を参照する
4. MainActivity.java を編集
MainActivity.java
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
// QR コードを Bitmap で生成する Bitmap bmpQr = generateQrCode("はろー, QR code", 400); // Bitmap を ImageView にセットする ImageView ivQrCode = findViewById(R.id.ivQrCode); ivQrCode.setImageBitmap(bmpQr);
}
// QR コードの Bitmap を生成する private static Bitmap generateQrCode(String text, int sideLength) { int width, height; width = height = sideLength; Map<EncodeHintType, Object> encHint = new HashMap<>(); encHint.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // UTF-8 に対応させる encHint.put(EncodeHintType.MARGIN, 1); // 枠の太さを1にする(デフォルトは4) // BitMatrix に QR コードを生成 BitMatrix bitMatrix; try { QRCodeWriter qrCodeWriter = new QRCodeWriter(); bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, encHint); } catch (WriterException e) { return null; // Error. } // Bitmap を生成して BitMatrix から転写 BarcodeEncoder barcodeEncoder = new BarcodeEncoder(); return barcodeEncoder.createBitmap(bitMatrix); }
}