Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีปิดปุ่ม Back ใน Android ขณะ Logout ด้วย Kotlin

ปิดใช้งานปุ่ม Back เพื่อป้องกันการกลับสู่หน้าที่ต้อง Login

ตัวอย่างนี้สาธิตวิธี Override onBackPressed() เพื่อปิดใช้งานปุ่ม Back ใน Android เมื่อผู้ใช้ Logout แล้ว โดยใช้ Kotlin

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

สร้างโปรเจกต์ Android ใหม่ใน Android Studio

ขั้นตอนที่ 2: เลย์เอาต์ (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>

ขั้นตอนที่ 3: โค้ดปิดปุ่ม Back (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() {
        // ไม่เรียก super.onBackPressed() เพื่อปิดการทำงานปกติ
        Toast.makeText(applicationContext, "Disabled Back Press", Toast.LENGTH_SHORT).show()
    }
}

ขั้นตอนที่ 4: Manifest

<?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>

แนวทางปฏิบัติที่ดีกว่าสำหรับ Logout

  • Clear Back Stack: ใช้ Intent.FLAG_ACTIVITY_CLEAR_TOP และ FLAG_ACTIVITY_NEW_TASK เมื่อไปหน้า Login
  • Finish Affinity: finishAffinity() (API 16+) ปิด Activity ทั้งหมดใน Task
  • OnBackPressedDispatcher (AndroidX): ใช้ onBackPressedDispatcher.addCallback สำหรับการจัดการทันสมัย

การ Override onBackPressed() แบบง่ายนี้เหมาะสำหรับกรณีเฉพาะเจาะจง แต่ควรพิจารณา UX ให้ดีกว่านี้