ユーザ用ツール

タイトルバーのカスタマイズ

概要

AndroidはHoneyComb(3.0)以降、ActionBarというスタイルのタイトルになり、iPhoneライクなボタン配置を容易に行うことが出来るようになっている。

ここでは、ActionBarではなく、GingerBread(2.3)以前のバージョンでも利用できるタイトルバーをカスタマイズしてボタンを配置する方法である。

Android 11が最新版である2021年現在において、ActionBarは既に使われない技術となっている。 Toolbarがこれに代わるものとして使用されており、同じく廃止されている「オプションボタン」に相当する、「…」ボタンを Toolbar上に提供する形になっている。1)

ActionBar同様に、他のボタンを配置することも可能である。

タイトルのカスタマイズ

そもそも、GingerBread以前であっても、タイトルを任意にカスタマイズしてボタンでも何でも配置できるようになっている。

任意のレイアウトを作成して、それを割り当てればタイトルバーは変更可能である。

具体的にはアクティビティの onCreate()で、次のようにすればいい。

private Window mWindow;

@Override
protected void onCreate(Bundle savedInstanceState) {

	super.onCreate(savedInstanceState);
	mWindow = getWindow();
	mWindow.requestFeature(Window.FEATURE_CUSTOM_TITLE);
	setContentView(R.layout.post_comment);
	mWindow.setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_with_button);

レイアウト、title_with_button.xmlはこんな感じで。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/titleLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false"
    android:gravity="center_vertical"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/txtTitle"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:ellipsize="end"
        android:gravity="center_vertical"
        android:maxLines="1"
        android:minHeight="40sp"
        android:text="TextView" />

    <Button
        android:id="@+id/btnPost"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_weight="0"
        android:gravity="fill_vertical"
        android:text="@string/btn_label_post" />

</LinearLayout>

requestFeature()はsetContentView()の前に行う必要がある。 これはタイトルのカスタマイズ内容の如何に関わらず必ずである。

しかし、ただこれを行っただけでは実は問題がある。 ボタンなど、最低の高さが単純なテキストより高いアイテムを配置すると、タイトルバーに収まりきらないからだ。

高さのカスタマイズは、アクティビティのテーマで行う必要がある。

タイトルに、任意のウィジェットを配置する、ここまでの方法は、実はあちこちにサンプルとして書かれているが、この高さを変更する下りまで書いてあるところはほとんど存在しない。

おそらくは、Androidのアプリ開発に置いては、当たり前のことなのだろう。

さんざん探し回った結果、ここに、このことに関する記述があるのをようやく見つけた。

高さの変更

高さの設定は、スタイルによって行う。styles.xmlに次のようなエントリを作る。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="customized_title">
        <item name="android:windowTitleSize">40sp</item>
    </style>
</resources>

これを、そのタイトルを使いたいアクティビティのテーマとして設定するだけである。 具体的には、Manifestファイルで、次のように割り当てる。

<activity android:name=".FBPostMessage" android:theme="@style/customized_title"></activity>

これで、次のような高さがきちんと収まった画面を得ることが出来る。

Androidに関してへ戻る。

1)
もちろん、オプションが不要な場合にはボタンを置かないことも可能である。

This website uses cookies. By using the website, you agree with storing cookies on your computer. Also, you acknowledge that you have read and understand our Privacy Policy. If you do not agree, please leave the website.

More information