Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Tạo Custom ActionBar/Toolbar trong Android

ActionBar (nay thường dùng Toolbar) là thanh điều hướng trên cùng màn hình. Custom Toolbar cho phép thiết kế tự do: logo, title, menu, search, avatar... thay vì dùng ActionBar mặc định.

Cách 1: Toolbar trong Layout (Khuyến nghị)

Bước 1: Theme không ActionBar mặc định


Bước 2: Layout toolbar_custom.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:id="@+id/customToolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:contentInsetStart="0dp"
    app:contentInsetLeft="0dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:paddingHorizontal="16dp">

        <ImageView
            android:id="@+id/ivLogo"
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:src="@drawable/ic_logo"
            android:contentDescription="Logo" />

        <TextView
            android:id="@+id/tvTitle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginStart="12dp"
            android:text="Tên App"
            android:textColor="@android:color/white"
            android:textSize="20sp"
            android:textStyle="bold" />

        <ImageView
            android:id="@+id/ivSearch"
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:layout_marginEnd="8dp"
            android:src="@drawable/ic_search" />

        <ImageView
            android:id="@+id/ivNotification"
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:src="@drawable/ic_notifications" />
    </LinearLayout>
</androidx.appcompat.widget.Toolbar>

Bước 3: Include vào activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <include layout="@layout/toolbar_custom" />
    </com.google.android.material.appbar.AppBarLayout>

    <!-- Content main -->
    <include layout="@layout/content_main" 
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>

Bước 4: MainActivity.java

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

public class MainActivity extends AppCompatActivity {
    private Toolbar toolbar;
    private TextView tvTitle;
    private ImageView ivSearch, ivNotification;

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

        toolbar = findViewById(R.id.customToolbar);
        setSupportActionBar(toolbar); // Quan trọng: set làm support action bar

        // Tắt title mặc định (nếu không muốn)
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        
        // Bật home/up button nếu cần
        // getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        // Bind custom views
        tvTitle = toolbar.findViewById(R.id.tvTitle);
        ivSearch = toolbar.findViewById(R.id.ivSearch);
        ivNotification = toolbar.findViewById(R.id.ivNotification);

        // Xử lý click
        tvTitle.setOnClickListener(v -> Toast.makeText(this, "Click title", Toast.LENGTH_SHORT).show());
        ivSearch.setOnClickListener(v -> Toast.makeText(this, "Mở tìm kiếm", Toast.LENGTH_SHORT).show());
        ivNotification.setOnClickListener(v -> Toast.makeText(this, "Mở thông báo", Toast.LENGTH_SHORT).show());
    }

    // Menu mặc định (nếu vẫn dùng menu resource)
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            // Xử lý back/up
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Cách 2: Custom ActionBar cũ (Deprecated)

Chỉ dùng cho maintenance legacy code:

// Trong onCreate()
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.custom_action_bar);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setElevation(0); // Bỏ shadow

View customView = getSupportActionBar().getCustomView();
TextView tvTitle = customView.findViewById(R.id.tvTitle);
// ... xử lý view

Menu Resource (res/menu/main_menu.xml)

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_settings"
        android:title="Cài đặt"
        android:icon="@drawable/ic_settings"
        app:showAsAction="never" />
    <item
        android:id="@+id/action_help"
        android:title="Trợ giúp"
        app:showAsAction="never" />
</menu>

Toolbar với Collapsing AppBar (Material Design)

<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="250dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <com.google.android.material.appbar.CollapsingToolbarLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_scrollFlags="scroll|exitUntilCollapsed"
        app:titleEnabled="false"
        app:contentScrim="?attr/colorPrimary">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            android:src="@drawable/header_bg"
            app:layout_collapseMode="parallax" />

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
    </com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>

Chạy ứng dụng

App hiển thị Toolbar tùy chỉnh với logo, title, icon search, notification. Click các view trong toolbar xử lý sự kiện bình thường. Menu 3 chấm vẫn hoạt động nếu cần.

Best Practices

  • Luôn dùng Theme.NoActionBar và tự add Toolbar
  • Dùng setSupportActionBar() để tích hợp với hệ thống menu/up navigation
  • Tắt elevation nếu muốn flat design: app:elevation="0dp" hoặc setElevation(0)
  • Content inset: app:contentInsetStart="0dp" để logo sát mép trái
  • Accessibility: contentDescription cho ImageView, text size ≥ 14sp