반응형
How to Resolve the Deprecate of onBackPressed
API 33부터는 onBackPressed가 deprecated가 되어 더 이상 호출되지 않습니다. 때문에 이를 해결할 방법이 필요합니다.
OnBackPressedCallback
이를 해결하기 위해서는 이제 override 함수가 아닌 callback 선언을 통하여 사용해주어야 합니다.
// back key 처리를 위한 handler 선언
private val hndlBackPress = object:OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
Log.d("hndlBackPress", "back key pressed!!")
}
}
이후 onCreate에서 이를 연결해 주면, back key를 누를 때마다 선언된 hndlBackPress가 실행되게 됩니다.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_to)
this.onBackPressedDispatcher.addCallback(this, hndlBackPress)
}
테스트 전체 소스
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.Kotlin"
tools:targetApi="31">
<!-- FromActivity.kt 선언. 메인 페이지 (실행 시 처음 뜨는 Activity) -->
<activity
android:name=".FromActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.Kotlin.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_from.xml
<?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=".FromActivity">
<Button
android:id="@+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="NEXT"
/>
</RelativeLayout>
FromActivity.kt
package net.royfactory.kotlin
import android.os.Bundle
import android.util.Log
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.app.AppCompatActivity
class FromActivity : AppCompatActivity() {
private val hndlBackPress = object: OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
Log.d("hndlBackPress", "back key pressed!!")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_from)
this.onBackPressedDispatcher.addCallback(this, hndlBackPress)
}
}
반응형
'개발 창고 > Android' 카테고리의 다른 글
[Kotlin] A Variety of Brief Knowledge #1 (0) | 2023.11.26 |
---|---|
[Kotlin] How to Extract Initial Consonants (1) | 2023.11.25 |
[Android] How to use launchMode (0) | 2023.11.24 |
[Kotlin] How to check the resume and pause of all activities (2) | 2023.11.23 |
[Android] How to debug web views in Chrome (0) | 2023.11.22 |