Contenidos
Asegúrate de tener las dependencias necesarias en tu archivo build.gradle
1 2 3 |
implementation("com.google.zxing:core:3.4.1") implementation("androidx.appcompat:appcompat:1.3.1") implementation("com.journeyapps:zxing-android-embedded:4.2.0") |
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 31 32 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Texto para generar el QR" android:layout_margin="16dp"/> <Button android:id="@+id/generateButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Generar QR" android:layout_below="@id/editText" android:layout_centerHorizontal="true" android:layout_marginTop="16dp"/> <ImageView android:id="@+id/qrImageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/generateButton" android:layout_centerHorizontal="true" android:layout_marginTop="24dp"/> </RelativeLayout> |
MainActivity.kt
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
package com.example.myapplication import android.graphics.Bitmap import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.ImageView import androidx.appcompat.app.AppCompatActivity import com.google.zxing.BarcodeFormat import com.google.zxing.WriterException import com.google.zxing.common.BitMatrix import com.google.zxing.qrcode.QRCodeWriter class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val editText = findViewById<EditText>(R.id.editText) val generateButton = findViewById<Button>(R.id.generateButton) val qrImageView = findViewById<ImageView>(R.id.qrImageView) generateButton.setOnClickListener { val text = editText.text.toString() if (text.isNotEmpty()) { val bitmap = generateQRCode(text) qrImageView.setImageBitmap(bitmap) } } } private fun generateQRCode(text: String): Bitmap? { val qrCodeWriter = QRCodeWriter() try { val bitMatrix: BitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, 512, 512) val width: Int = bitMatrix.width val height: Int = bitMatrix.height val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565) for (x in 0 until width) { for (y in 0 until height) { bitmap.setPixel(x, y, if (bitMatrix[x, y]) 0xFF000000.toInt() else 0xFFFFFFFF.toInt()) } } return bitmap } catch (e: WriterException) { e.printStackTrace() } return null } } |