0

Custom ActionBar on Android

Buat activity untuk ActionBar. Misal saya beri nama custom_actionbar_center.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@android:color/transparent">

    <TextView
        android:id="@+id/title_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:textSize="25sp"
        android:textColor="#fff"
        android:gravity="center"
        android:text="title"
        />

    <ImageButton
        android:id="@+id/ibtn_bluetooth"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginRight="15dp"
        android:layout_alignParentRight="true"
        android:foregroundGravity="center"
        android:background="@null"
        android:src="@drawable/ic_settings_white_32dp" />

</RelativeLayout>

Tambahkan code berikut pada activity

ActionBar mActionBar = getSupportActionBar();
assert mActionBar != null;
mActionBar.setDisplayShowHomeEnabled(false);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater mInflater = LayoutInflater.from(this);
View actionBar = mInflater.inflate(R.layout.custom_actionbar_center, null);
TextView mTitleTextView = actionBar.findViewById(R.id.title_text);
mTitleTextView.setText(R.string.app_name);
mActionBar.setCustomView(actionBar);
mActionBar.setDisplayShowCustomEnabled(true);
((Toolbar) actionBar.getParent()).setContentInsetsAbsolute(0,0);

Jika ingin menghilangkan shadow di bawah ActionBar, tambahkan code berikut pada activity:

getSupportActionBar().setElevation(0);