Giới thiệu
Action Bar (hay App Bar) là thanh tiêu đề ở đầu màn hình. Bài viết này hướng dẫn các cách ẩn nó: ẩn thủ công trong code, hoặc dùng theme không có Action Bar.
Cách 1: Ẩn trong code (Java/Kotlin)
// Java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
}
// Kotlin
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportActionBar?.hide()
}
Cách 2: Dùng Theme không có Action Bar (Khuyến nghị)
Trong res/values/themes.xml (hoặc styles.xml):
<style name="Theme.MyApp.NoActionBar" parent="Theme.MaterialComponents.DayNight.NoActionBar">
<!-- Customize your theme here -->
</style>
Áp dụng trong AndroidManifest.xml:
<activity
android:name=".MainActivity"
android:theme="@style/Theme.MyApp.NoActionBar"
android:exported="true">
...
</activity>
Cách 3: Ẩn cho toàn bộ ứng dụng
Trong AndroidManifest.xml, set theme cho <application>:
<application
android:theme="@style/Theme.MaterialComponents.DayNight.NoActionBar"
...>
...
</application>
Lưu ý
- Nếu dùng
getSupportActionBar().hide(), Action Bar vẫn được tạo rồi ẩn -> gây chớp mắt (flicker) lúc khởi động. Cách dùng Theme NoActionBar tốt hơn. - Nếu dùng
Toolbartùy chỉnh, hãy dùngsetSupportActionBar(toolbar)và theme NoActionBar. - Trên Android 11+, các flag fullscreen cũ bị deprecated, hãy dùng
WindowInsetsControllernhư bài trước.
Ví dụ layout đơn giản (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:background="#000000">
<DigitalClock
android:id="@+id/digitalClock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="48sp"
android:textColor="#FFFFFF" />
</LinearLayout>