C/C++プログラマの管理者が, Androidプログラムにチャレンジ. AndroidプログラミングのTipsをメモっていく予定です.

テキストビュー(TextView)を継承するビューに表示する文字の位置を変更する方法は2通りある.
以下では, テキストビューで文字位置を変更しているが, テキストビューを継承する他のビューでも同様に文字位置を変更できる.



XMLファイルにより設定

  • res/layout/main.xml
    • android:gravity属性に"left", "center, "right", "top", "bottom"を組み合わせて, 文字の表示位置を設定する.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <TextView android:id="@+id/text01_id"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:height="50sp"
    android:background="#FFFFFF"
    android:textColor="#000000"
    android:text="CENTER"
    android:gravity="center"
    />
  <TextView android:id="@+id/text02_id"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:height="50sp"
    android:background="#FF0000"
    android:textColor="#FFFFFF"
    android:text="RIGHT"
    android:gravity="right"
    />
  <TextView android:id="@+id/text03_id"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:height="50sp"
    android:background="#0000FF"
    android:textColor="#FFFFFF"
    android:text="TOP|CENTER"
    android:gravity="top|center"
    />
  <TextView android:id="@+id/text04_id"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:height="50sp"
    android:background="#00FF00"
    android:textColor="#000000"
    android:text="LEFT|BOTTOM"
    android:gravity="left|bottom"
    />
</LinearLayout>

コードにより設定

    • TextView#setGravityメソッドで, Gravity.{LEFT, CENTER, RIGHT, TOP, BOTTOM}を組み合わせて, 文字の表示位置を設定する.
package com.moonlight_aska.android.setgravity01;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.TextView;

public class SetGravity01 extends Activity {
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    TextView text01 = (TextView)findViewById(R.id.text01_id);
    text01.setText("CENTER");
    text01.setGravity(Gravity.CENTER);

    TextView text02 = (TextView)findViewById(R.id.text02_id);
    text02.setText("RIGHT");
    text02.setGravity(Gravity.RIGHT);

    TextView text03 = (TextView)findViewById(R.id.text03_id);
    text03.setText("TOP|CENTER");
    text03.setGravity(Gravity.TOP|Gravity.CENTER);

    TextView text04 = (TextView)findViewById(R.id.text04_id);
    text04.setText("LEFT|BOTTOM");
    text04.setGravity(Gravity.LEFT|Gravity.BOTTOM);
  }
}



コメントをかく


「http://」を含む投稿は禁止されています。

利用規約をご確認のうえご記入下さい

Menu


逆引き(基礎編)

画面表示/操作(49)

フラグメント(1)

逆引き(応用編)

Firebase(2)

AD



管理人/副管理人のみ編集できます