▼Androidメモ▼
テキストビューとイメージビュー


テキストビューとイメージビューを利用するプログラムを作成する。



リソース
プロジェクトの「res/drawable」に「sample.png」を配置。

sample.png


ソースコード
TextViewEx.java
package net.npaka.textviewex;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ImageView;

//テキストビューとイメージビュー
public class TextViewEx extends Activity {
    private final static int WC=LinearLayout.LayoutParams.WRAP_CONTENT;
    //初期化
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        //レイアウトの生成
        LinearLayout layout=new LinearLayout(this);
        layout.setBackgroundColor(Color.rgb(255,255,255));
        layout.setOrientation(LinearLayout.VERTICAL);
        setContentView(layout); 

        //テキストビューの生成
        TextView textView=new TextView(this);
        textView.setText("これはテストです");
        textView.setTextSize(16.0f);                  
        textView.setTextColor(Color.rgb(0,0,0));
        
        //コンポーネントのサイズの指定
        textView.setLayoutParams(new LinearLayout.LayoutParams(WC,WC));
        
        //レイアウトへのコンポーネントの追加
        layout.addView(textView);

        //画像の読み込み
        Bitmap bitmap=BitmapFactory.decodeResource(
            getResources(),R.drawable.sample);

        //イメージビューの生成
        ImageView imageView=new ImageView(this);
        imageView.setImageBitmap(bitmap);
        imageView.setLayoutParams(new LinearLayout.LayoutParams(WC,WC));
        layout.addView(imageView);
    }  
}

任意フォントの利用方法

assetにフォント(*.ttf)を追加し、setTypeface()でフォント指定。
        TextView textView=new TextView(this);
        textView.setText("アリーナの こうげき!");
        Typeface face=Typeface.createFromAsset(getAssets(),"DragonQuestFC.ttf");
        textView.setTypeface(face);
        textView.setTextSize(32.0f);                  
        textView.setTextColor(Color.WHITE);
        textView.setBackgroundColor(Color.BLACK);
        layout.addView(textView);


−戻る−