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

วิธีซ่อน Action Bar ใน Android

ภาพรวม

บทความนี้สาธิตวิธีซ่อน Action Bar (แถบแอปด้านบน) ใน Android โดยใช้ getSupportActionBar().hide()

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

Android Studio → File → New Project → Empty Activity

ขั้นตอนที่ 2: Layout (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:orientation="vertical"
    android:gravity="center"
    android:background="#000"
    tools:context=".MainActivity">

    <DigitalClock
        android:id="@+id/digital"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:textColor="#FFF" />

</LinearLayout>

ขั้นตอนที่ 3: โค้ดหลัก (java/MainActivity.java)

package com.example.myapplication;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // ซ่อน Action Bar
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
    }
}

วิธีอื่น: ใช้ Theme ไม่มี Action Bar

ใน res/values/themes.xml (หรือ styles.xml แบบเก่า):

<style name="Theme.MyApp.NoActionBar" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    <!-- ปรับแต่งสีและสไตล์อื่นๆ ที่นี่ -->
</style>

แล้วใน AndroidManifest.xml:

<activity
    android:name=".MainActivity"
    android:theme="@style/Theme.MyApp.NoActionBar">
    ...
</activity>

ความแตกต่าง

วิธีข้อดีข้อเสีย
hide() ในโค้ดควบคุมได้แบบไดนามิก (ซ่อน/แสดงได้)อาจเห็น Action Bar กระพริบตอนเริ่มต้น
Theme NoActionBarไม่มีการกระพริบ เนื่องจากไม่มี Action Bar ตั้งแต่แรกไม่สามารถแสดง Action Bar ได้ใน Activity นั้น

ทดสอบ

รันแอป จะไม่เห็นแถบ Action Bar ด้านบน มีเฉพาะ DigitalClock อยู่ตรงกลางจอ