ภาพรวม
บทความนี้สาธิตวิธีปิดการแสดง Title ใน Action Bar โดยใช้ setDisplayShowTitleEnabled(false)
ขั้นตอนที่ 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: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"
android:gravity="center"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="30sp"
android:gravity="center" />
</LinearLayout>
ขั้นตอนที่ 3: โค้ดหลัก (java/MainActivity.java)
package com.example.myapplication;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle("หน้าหลัก");
getSupportActionBar().setSubtitle("ยินดีต้อนรับ");
getSupportActionBar().setDisplayShowTitleEnabled(false); // ซ่อน Title และ Subtitle
}
textView.setText("Action Bar Title ถูกปิดการแสดงแล้ว");
}
}
ผลลัพธ์
- Title ("หน้าหลัก") และ Subtitle ("ยินดีต้อนรับ") จะไม่แสดง
- Action Bar ยังคงอยู่ (มีพื้นที่ สีพื้นหลัง)
- ปุ่ม Home/Up และ Menu items ยังทำงานได้
วิธีอื่นๆ
1. ใช้ Theme NoActionBar (แนะนำ)
<style name="Theme.App.NoActionBar" parent="Theme.MaterialComponents.DayNight.NoActionBar"> </style>
ใน Manifest: android:theme="@style/Theme.App.NoActionBar"
2. ซ่อน Action Bar ทั้งหมด
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
3. ใช้ Toolbar แทน (ควบคุมได้เต็มที่)
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary" />
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// ไม่ต้อง setTitle() ก็ได้ หรือ setTitle("")
ความแตกต่าง
| วิธี | Action Bar ยังมีอยู่? | ใช้ได้กับ Toolbar? |
|---|---|---|
| setDisplayShowTitleEnabled(false) | ใช่ | ใช่ |
| Theme NoActionBar | ไม่ (ไม่มี Action Bar) | ใช้ Toolbar แทน |
| hide() | ไม่ (ซ่อนหมด) | N/A |
ทดสอบ
รันแอป จะเห็น Action Bar มีแต่พื้นที่สี ไม่มีข้อความ Title/Subtitle