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

วิธีซ่อน Status Bar ใน Android ด้วย Kotlin

ภาพรวม

ตัวอย่างนี้สาธิตวิธีการซ่อน Status Bar (แถบสถานะบนสุด) ใน Android Activity โดยใช้ WindowManager.LayoutParams.FLAG_FULLSCREEN และ Kotlin

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

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

ขั้นตอนที่ 2: จัดรูปแบบหน้าจอหลัก (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    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>

ขั้นตอนที่ 3: เขียนโค้ด MainActivity.kt

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Window
import android.view.WindowManager

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // ซ่อน Title Bar
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        // ซ่อน Status Bar - ทำให้แอปเต็มหน้าจอ
        window.setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN
        )
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
    }
}

ขั้นตอนที่ 4: ตั้งค่า AndroidManifest.xml

ใช้การตั้งค่ามาตรฐาน

ทดสอบการทำงาน

รันแอปบนอุปกรณ์จริง Status Bar จะถูกซ่อน แอปจะแสดงเต็มหน้าจอ

วิธีอื่นๆ

  • Theme/Style: ใช้ Theme `Theme.AppCompat.Light.NoActionBar.FullScreen` ใน Manifest
  • Immersive Mode: ใช้ `SYSTEM_UI_FLAG_IMMERSIVE_STICKY` (เหมือนบทความก่อนหน้า) สำหรับซ่อนทั้ง Status Bar และ Navigation Bar
  • WindowInsetsController (API 30+): วิธีใหม่ที่แนะนำสำหรับควบคุม System Bars