Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách ẩn vĩnh viễn Navigation Bar trong Activity Android bằng Kotlin

Giới thiệu

Bài viết hướng dẫn cách ẩn thanh điều hướng (Navigation Bar - nút Back, Home, Recent) vĩnh viễn trong một Activity, tạo trải nghiệm toàn màn hình (immersive mode) bằng Kotlin.

Các bước thực hiện

Bước 1: Tạo dự án mới

Android Studio > File > New Project.

Bước 2: Layout (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="70dp"
        android:background="#008080"
        android:padding="5dp"
        android:text="TutorialsPoint"
        android:textColor="#fff"
        android:textSize="24sp"
        android:textStyle="bold" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Hello World!"
        android:textColor="@android:color/holo_blue_dark"
        android:textSize="24sp"
        android:textStyle="bold" />

</RelativeLayout>

Bước 3: MainActivity.kt - Immersive Mode

import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity

@Suppress("DEPRECATED_IDENTITY_EQUALS", "DEPRECATION")
class MainActivity : AppCompatActivity() {
    private var currentApiVersion = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"

        currentApiVersion = Build.VERSION.SDK_INT
        hideNavigationBar()

        if (currentApiVersion >= Build.VERSION_CODES.KITKAT) {
            val decorView = window.decorView
            decorView.setOnSystemUiVisibilityChangeListener { visibility ->
                if (visibility and View.SYSTEM_UI_FLAG_FULLSCREEN == 0) {
                    hideNavigationBar()
                }
            }
        }
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (currentApiVersion >= Build.VERSION_CODES.KITKAT && hasFocus) {
            hideNavigationBar()
        }
    }

    private fun hideNavigationBar() {
        val flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
            View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
            View.SYSTEM_UI_FLAG_FULLSCREEN or
            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY

        window.decorView.systemUiVisibility = flags
    }
}

Bước 4: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.hidenavbar">

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

Giải thích các Flag quan trọng

  • SYSTEM_UI_FLAG_IMMERSIVE_STICKY: Navigation bar ẩn nhưng hiện lại khi người dùng vuốt từ cạnh màn hình, rồi tự ẩn lại (sticky).
  • SYSTEM_UI_FLAG_HIDE_NAVIGATION: Ẩn navigation bar.
  • SYSTEM_UI_FLAG_FULLSCREEN: Ẩn status bar.
  • SYSTEM_UI_FLAG_LAYOUT_*: Cho phép layout vẽ đầy đủ màn hình bao gồm khu vực system bar.

Lưu ý quan trọng

  • Gọi hideNavigationBar() trong cả onCreate, onWindowFocusChanged và listener OnSystemUiVisibilityChangeListener để đảm bảo bar luôn ẩn khi app lấy focus trở lại.
  • Từ Android 11 (API 30), các API này vẫn hoạt động nhưng Google khuyến khích dùng WindowInsetsController (thuộc Jetpack WindowManager).
  • Cách hiện đại (API 30+):
// Trong Activity (API 30+)
window.setDecorFitsSystemWindows(false)
window.insetsController?.apply {
    hide(WindowInsets.Type.navigationBars() or WindowInsets.Type.statusBars())
    systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
}