본문 바로가기

개발 일기/Android

[Kotlin] Floating Button 과 QRCODE 인식

AndroidManifest.xml

<manifest>
	<uses-sdk tools:overrideLibrary="com.google.zxing.client.android" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application>
    	<activity android:name="com.journeyapps.barcodescanner.CaptureActivity"
            android:screenOrientation="fullSensor"
            tools:replace="screenOrientation"/>
    </application>
</manifest>

 

build.gradle (Module: app)

dependencies{
	implementation('com.journeyapps:zxing-android-embedded:3.6.0') 
    { transitive = false }
    implementation 'com.google.zxing:core:3.3.2'
}

안드로이드 버전별로 쓰는게 다른듯??

 

MainActivity.kt

class MainActivity : AppCompatActivity() {
    private var url = "https://url"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        supportActionBar?.hide()

        val floatButton = Main_FloatingActionButton_floating //Floating 버튼
        floatButton.setOnClickListener { click ->
            val qr = IntentIntegrator(this)//QR스캔 창으로 넘어감 
            qr.setOrientationLocked(false)
            qr.initiateScan()
        }
    }

    override fun onResume() {
        super.onResume()
        loadWebView()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
        if(result!= null){
            if(result.contents == null) {
                Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show()
            } else {
                Toast.makeText(this, "Scanned: " + result.contents, 
                Toast.LENGTH_LONG).show()
                url = result.contents
            }
        }else{
            super.onActivityResult(requestCode, resultCode, data)
        }
    }

    private fun loadWebView(){
        val webView = Main_WebView_view as WebView
        val settings = webView.settings

        settings.javaScriptEnabled= true
        settings.databaseEnabled = true
        webView.webChromeClient = WebChromeClient()//자바스크립트의 alert 창 띄워줌.
        webView.webViewClient = WebViewClient()//다른 웹 브라우져로 넘어가는 것 방지

        webView.loadUrl(url)
    }
}

zxing 쓰면 쉽게 QR코드 인식이 된다.

 

activity_main.xml

<com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/Main_FloatingActionButton_floating"
        android:src="@drawable/ic_camera_white_24dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_margin="20dp"
        app:backgroundTint="@color/colorPrimary"
        app:tint="@color/colorWhite"/>

app:tint="@null" 하면 배경 없는 이미지 넣기 가능!

app으로 안해주면 버튼이 무조건 검정색으로만 표시된다. 주의하자!