Android の ActionBar に画像を表示

ActionBar にオリジナルのレイアウトを適用し画像を表示する。

action_bar.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="48dp">

    <ImageView
        android:id="@+id/logo_action_bar"
        android:layout_width="match_parent"
        android:layout_height="32dp"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="8dp"
        android:scaleType="fitStart"
        android:src="@drawable/logo_action_bar"/>

</RelativeLayout>

Activityで適用

public class XxxActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ・・・

        // 表示するlayoutファイルの取得
        LayoutInflater inflater = LayoutInflater.from(this);
        View actionBarView = inflater.inflate(R.layout.action_bar, null);

        // プログラムでオリジナル画像を設定するなら下記
        // ((ImageView)actionBarView.findViewById(R.id.logo_action_bar)).setImageDrawable(getDrawable(R.drawable.xxxx));

        ActionBar actionBar = getSupportActionBar();
        actionBar.setCustomView(actionBarView);
        actionBar.setDisplayShowCustomEnabled(true);


コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

CAPTCHA