Ví dụ này minh họa cách ẩn Navigation Bar (nút Back, Home, Recent) để tạo trải nghiệm fullscreen immersive bằng Kotlin.
Bước 1: Tạo dự án mới
Tạo dự án mới trong Android Studio, chọn Kotlin.
Bước 2: Layout (res/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="50dp"
android:padding="8dp"
android:text="Tutorials Point"
android:textColor="@color/colorPrimaryDark"
android:textSize="48sp"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Đã ẩn Home và các nút hệ thống"
android:textAlignment="center"
android:textColor="@android:color/background_dark"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
Bước 3: MainActivity.kt
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import java.util.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) hideNavigationBar()
}
private fun hideNavigationBar() {
val decorView = window.decorView
val uiOptions = (View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_FULLSCREEN
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) // Quan trọng: giữ immersive mode
// Dùng timer để liên tục apply flags (hệ thống có thể reset)
val timer = Timer()
timer.scheduleAtFixedRate(object : TimerTask() {
override fun run() {
runOnUiThread { decorView.systemUiVisibility = uiOptions }
}
}, 1, 2)
}
}
Lưu ý: Cần flag IMMERSIVE_STICKY để navigation bar ẩn vĩnh viễn (chỉ hiện lại khi swipe từ cạnh màn hình).
Bước 4: Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.q1">
<application ...>
<activity android:name=".MainActivity">...</activity>
</application>
</manifest>
Chạy ứng dụng
App chạy fullscreen, navigation bar ẩn. Vuốt từ đáy màn hình lên để hiện lại tạm thời.