文字サイズの設定

広告

表示される文字列の文字のサイズを設定する方法を確認します。「TextView」クラスで用意されている「setTextSize」メソッドを使います。

Set the default text size to the given value, interpreted as "scaled 
pixel" units. This size is adjusted based on the current density and 
user font size preference.

Related XML Attributes:
  android:textSize

Parameters:
  size  The scaled pixel size.

1番目の引数に文字サイズをfloat型の値で指定します。単位はピクセルです。

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

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

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

        TextView tv = new TextView(this);
        tv.setText("Text");
        tv.setTextSize(12.0f);
        setContentView(tv);
    }
}

サンプルプログラム

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

Test05_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;

public class Test05_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("ABCDefg 12.0f");
        tv1.setTextSize(12.0f);
        linearLayout.addView(tv1, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));

        TextView tv2 = new TextView(this);
        tv2.setText("ABCDefg 18.0f");
        tv2.setTextSize(18.0f);
        linearLayout.addView(tv2, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));

        TextView tv3 = new TextView(this);
        tv3.setText("ABCDefg 32.0f");
        tv3.setTextSize(32.0f);
        linearLayout.addView(tv3, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
    }
}

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

文字サイズの設定

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

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