Android
 Computer >> コンピューター >  >> プログラミング >> Android

AndroidのActionBarにカスタムビューを表示する方法をステップ解説

ActionBarにカスタムビューを表示するには?

このチュートリアルでは、AndroidアプリのActionBar(アクションバー)に独自のカスタムビューを表示する方法を、サンプルコードとともに解説します。

カスタムビューを活用すれば、デフォルトのタイトル表示だけでは実現できない、ロゴやタイトル、アイコンを自由に配置したオリジナルのヘッダーを作成できます。

実装手順

ステップ1:新規プロジェクトを作成する

Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成しましょう。

ステップ2: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"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Custom Action Bar"
        android:textSize="20sp"/>
</LinearLayout>

ステップ3:res/layout/custom_action_bar.xml を作成する

続いて、ActionBarに表示するカスタムビュー用のレイアウトファイルを作成します。ここでは、左側にアイコンとタイトル(TextView)、右側に2つのアイコン(ImageView)を配置した、Instagram風のヘッダーを定義しています。

<?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:gravity="center_vertical"
    android:padding="10dp"
    android:weightSum="1">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="0.6">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"/>

        <TextView
            android:id="@+id/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:text="Instagram"
            android:textSize="20sp"
            android:textColor="#000"
            android:textStyle="bold"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginRight="10dp"
        android:layout_weight="0.4"
        android:gravity="end">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"/>

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginLeft="20dp"/>
    </LinearLayout>
</LinearLayout>

ステップ4:src/MainActivity.java を編集する

Activity側では、ActionBarの表示オプションを「DISPLAY_SHOW_CUSTOM」に変更し、作成したレイアウトをカスタムビューとしてセットします。さらに、タイトル部分(TextView)にクリックイベントを追加しています。

package com.example.sample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        // ActionBarをカスタムビュー表示モードに切り替える
        this.getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setCustomView(R.layout.custom_action_bar);
        //getSupportActionBar().setElevation(0);

        // カスタムビュー内のTextViewにクリックイベントを設定
        View view = getSupportActionBar().getCustomView();
        TextView name = view.findViewById(R.id.name);
        name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "You have clicked tittle", Toast.LENGTH_LONG).show();
            }
        });
    }
}

ポイント解説:

  • setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM):ActionBarをカスタムビュー表示モードに切り替えます。
  • setDisplayShowCustomEnabled(true):カスタムビューの表示を有効にします。
  • setCustomView(R.layout.custom_action_bar):ActionBarに表示するレイアウトを指定します。

なお、上記のコードは旧サポートライブラリ(android.support.v7)を使用しています。最新のAndroid Studio環境では、androidx.appcompat.app.AppCompatActivity および androidx.appcompat.app.ActionBar に読み替えてください。

ステップ5:Manifests/AndroidManifest.xml を確認する

マニフェストファイルは以下のようになります。カスタムActionBarの表示に特別な権限は必要ありません。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.sample">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

アプリを実行して動作を確認しよう

それでは、アプリを実行してみましょう。ここでは、実機のAndroidスマートフォンがパソコンに接続されているものとして説明を進めます。

Android Studioからアプリを実行するには、プロジェクト内のいずれかのアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。実行デバイスとして自分のスマートフォンを選択すると、端末の画面にカスタムアクションバーが表示されます。

AndroidのActionBarにカスタムビューを表示する方法をステップ解説

  1. AndroidのカスタムListViewに検索機能を実装する方法【サンプルコード付き】

    はじめに このチュートリアルでは、AndroidアプリのListView(リストビュー)に検索機能を実装する方法を解説します。EditTextに入力した文字列に応じて、表示中のリスト項目をリアルタイムで絞り込む仕組みを作成します。 手順1:新規プロジェクトを作成する Android Studioを開き、「File」→「New Project」を選択して、必要な項目をすべて入力し、新しいプロジェクトを作成します。 手順2:レイアウトファイル(activity_main.xml)を編集する res/layout/activity_main.xml に以下のコードを記述します。上部に検索ワードを入力

  2. 【Android】カスタムAlertDialogビューを実装する完全ガイド

    この記事では、AndroidアプリでカスタムAlertDialog(ダイアログ)を実装する方法を、サンプルコード付きで段階的に解説します。標準的なダイアログではなく、独自のレイアウトを持つダイアログを表示したい場合に役立つ内容です。 ステップ1:新規プロジェクトの作成 まず、Android Studioを起動し、「File」⇒「New Project」を選択して新しいプロジェクトを作成します。必要な項目をすべて入力してプロジェクトの雛形を生成しましょう。 ステップ2:activity_main.xml にコードを追加 res/layout/activity_main.xml に以下のコードを記