文字列の水平方向の表示位置を設定

広告

文字列を表示する時に表示エリアのどの位置に表示するのかを設定する方法を確認します。「TextView」クラスで用意されている「setAlignment」メソッドを使います。

Sets the alignment of this view's text. Valid values are defined in 
Layout.

Related XML Attributes:
  android:textAlign

Parameters:
  align  水平位置

引数には水平位置を表す「android.text.Layout.Alignment」クラスで用意されている定数を指定します。指定可能な定数は次の3つです。

Alignment  Alignment.ALIGN_CENTER
Alignment  Alignment.ALIGN_NORMAL
Alignment  Alignment.ALIGN_OPPOSITE

「ALIGN_NORMAL」は通常位置(現在の環境であれば左寄せ)、「ALIGN_CENTER」は中央位置、「ALIGN_OPPOSITE」は通常とは逆の位置(現在の環境であれば右寄せ)となります。値はAlignmentクラスのオブジェクトとして定義されています。

具体的には次のように記述します。

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.text.Layout.Alignment;

public class Test extends Activity {
    @Override protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        TextView tv = new TextView(this);
        tv.setText("Text");
        tv.setAlignment(Alignment.ALIGN_CENTER);
        setContentView(tv);
    }
}

サンプルプログラム

それでは実際に試してみます。プロジェクトを作成しソースコードを次のように変更しました。

Test10_01.java

package jp.javadrive.android;

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.view.ViewGroup;
import android.widget.TextView;
import android.graphics.Color;
import android.text.Layout.Alignment;

public class Test10_01 extends Activity
{
    private final int WRAP_CONTENT = ViewGroup.LayoutParams.WRAP_CONTENT; 

    @Override protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        setContentView(linearLayout);

        TextView tv1 = new TextView(this);
        tv1.setText("Android");
        tv1.setWidth(150);
        tv1.setBackgroundColor(Color.LTGRAY);
        tv1.setAlignment(Alignment.ALIGN_NORMAL);
        linearLayout.addView(tv1, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));

        TextView tv2 = new TextView(this);
        tv2.setText("Android");
        tv2.setWidth(150);
        tv2.setBackgroundColor(Color.GREEN);
        tv2.setAlignment(Alignment.ALIGN_CENTER);
        linearLayout.addView(tv2, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));

        TextView tv3 = new TextView(this);
        tv3.setText("Android");
        tv3.setWidth(150);
        tv3.setBackgroundColor(Color.LTGRAY);
        tv3.setAlignment(Alignment.ALIGN_OPPOSITE);
        linearLayout.addView(tv3, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
    }
}

ビルド後にエミュレーター上で実行します。

水平方向の表示位置の設定

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

プログラミングや開発環境構築の解説サイトを運営しています。