スタイルを設定

広告

フォントのスタイルとしてボールド及びイタリックが用意されています。各スタイルは定数として定義されています。

Typeface  Typeface.DEFAULT
Typeface  Typeface.DEFAULT_BOLD
Typeface  Typeface.DEFAULT_BOLD_ITALIC
Typeface  Typeface.DEFAULT_ITALIC

通常ノーマルと呼ばれているものが「Typeface.DEFAULT」です。ボールド(太字)にするには「Typeface.DEFAULT_BOLD」、イタリック(斜体)にするには「Typeface.DEFAULT_ITALIC」、ボールド+イタリックにするには「Typeface.DEFAULT_BOLD_ITALIC」を使用します。どの定数も値としてはTypefaceクラスのオブジェクトが設定されています。

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

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

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

        TextView tv = new TextView(this);
        tv.setText("Text");
        tv.setTypeface(Typeface.DEFAULT_BOLD);
        setContentView(tv);
    }
}

サンプルプログラム

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

Test02_01.java

package jp.javadrive.android;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.LinearLayout;
import android.view.ViewGroup;
import android.graphics.Typeface;

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

    /** Called with the activity is first created. */
    @Override
    public 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("DEFAULT");
        tv1.setTypeface(Typeface.DEFAULT );
        linearLayout.addView(tv1, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));

        TextView tv2 = new TextView(this);
        tv2.setText("DEFAULT_BOLD");
        tv2.setTypeface(Typeface.DEFAULT_BOLD);
        linearLayout.addView(tv2, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));

        TextView tv3 = new TextView(this);
        tv3.setText("DEFAULT_ITALIC");
        tv3.setTypeface(Typeface.DEFAULT_ITALIC);
        linearLayout.addView(tv3, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));

        TextView tv4 = new TextView(this);
        tv4.setText("DEFAULT_BOLD_ITALIC ");
        tv4.setTypeface(Typeface.DEFAULT_BOLD_ITALIC );
        linearLayout.addView(tv4, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
    }
}

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

スタイルを設定

試してみるとボールドは反映されますがイタリックは反映されていません。不具合なのか使用方法が悪いのか現時点ではわかっていません。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

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