2012年10月12日金曜日

タイトルバーの文字列をセンタリング

通常タイトルバーは左寄せで表示されることが多いですが、タイトルバーのレイアウトを XML で定義して変更することが可能です。今回は、タイトルバーの文字列をセンタリングしてみましょう。

CustomTitleBarTest1aActivity.java
package jp.co.triware.samples.CustomTitleBarTest1a;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;

public class CustomTitleBarTest1aActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // タイトルにレイアウトを指定する
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.main);

        // カスタマイズしたレイアウトファイルを指定
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);
    }
}
14行目の
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
で任意のレイアウトファイルを設定します。

設定するレイアウトファイルは18行目の
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);
で指定しています。

requestWindowFeatureメソッドはsetContentViewメソッドの前に設定してください。順番を入れ替えると設定値が反映されません。

titlebar.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/app_name"
        android:textColor="@android:color/white"
        />
</LinearLayout>

タイトルを表示させるTextViewを画面の横幅いっぱいに表示させて、TextView内で文字列をセンタリングしています。
色を指定しないと背景色に似た色で見づらいため、12行目で白色を指定しています。
android:textColor="@android:color/white"

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        />
</LinearLayout>

Androidプロジェクトの設定
プロジェクト名:CustomTitleBarTest1a
アプリケーション名:CustomTitleBarTest1a
パッケージ名:jp.co.triware.samples.CustomTitleBarTest1a
アクティビティーの作成:CustomTitleBarTest1aActivity
ビルドターゲットや最小SDKバージョンは、お使いの開発環境に合わせて設定してください。

実行結果
タイトルの文字列がセンタリングされています。

0 件のコメント:

コメントを投稿