Giới thiệu
Hướng dẫn này trình bày cách vô hiệu hóa nút Back (Back button) trên Android để ngăn người dùng quay lại màn hình trước sau khi đăng xuất, sử dụng override onBackPressed() và Kotlin.
Các bước thực hiện
Bước 1: Tạo dự án mới
Tạo project: File → New Project.
Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/image" />
</LinearLayout>
Bước 3: Xử lý logic (src/MainActivity.kt)
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onBackPressed() {
// Vô hiệu hóa back button: không gọi super.onBackPressed()
Toast.makeText(applicationContext, "Disabled Back Press", Toast.LENGTH_SHORT).show()
}
}
Bước 4: Cấu hình Manifest (androidManifest.xml)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Chạy ứng dụng
Kết nối thiết bị, nhấn Run. Nhấn nút Back vật lý hoặc gesture back → Toast "Disabled Back Press" hiện ra, Activity không bị finish.
Các trường hợp sử dụng thực tế
1. Sau khi đăng xuất (Logout)
class LoginActivity : AppCompatActivity() {
private var isLoggedOut = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Kiểm tra session, nếu đã logout thì clear back stack
if (isLoggedOut) {
// Không cho back về màn hình chính
}
}
override fun onBackPressed() {
if (isLoggedOut) {
// Không cho back, hoặc moveTaskToBack(true)
moveTaskToBack(true)
} else {
super.onBackPressed()
}
}
fun logout() {
isLoggedOut = true
// Clear token, sharedprefs...
// Chuyển về LoginActivity với flag CLEAR_TASK
val intent = Intent(this, LoginActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
}
startActivity(intent)
finish()
}
}
2. Double tap to exit (Nhấn 2 lần để thoát)
private var backPressedTime = 0L
override fun onBackPressed() {
if (System.currentTimeMillis() - backPressedTime < 2000) {
super.onBackPressed()
return
}
backPressedTime = System.currentTimeMillis()
Toast.makeText(this, "Press back again to exit", Toast.LENGTH_SHORT).show()
}
3. Confirmation Dialog trước khi thoát
override fun onBackPressed() {
AlertDialog.Builder(this)
.setTitle("Exit App")
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes") { _, _ ->
finishAffinity() // Hoặc System.exit(0)
}
.setNegativeButton("No", null)
.show()
}
API hiện đại: OnBackPressedDispatcher (AndroidX Activity 1.2+)
Thay vì override onBackPressed() (deprecated), dùng OnBackPressedCallback:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
if (isLoggedOut) {
Toast.makeText(this@MainActivity, "Back disabled", Toast.LENGTH_SHORT).show()
} else {
isEnabled = false // Tạm disable callback
onBackPressedDispatcher.onBackPressed() // Gọi default behavior
}
}
})
}
}
Lưu ý UX
- Vô hiệu hóa Back button hoàn toàn vi phạm nguyên tắc UX Android (Back phải luôn hoạt động dự đoán được).
- Chỉ disable trong trường hợp đặc biệt: màn hình login sau logout, payment flow, security screen.
- Luôn cung cấp cách thoát rõ ràng (nút Exit, Dialog xác nhận).
- Dùng
moveTaskToBack(true)thay vì disable hoàn toàn nếu muốn ẩn app.