たぼさんの部屋

いちょぼとのんびり

L003) TableLayoutで基本的なボタンを複数作る

目的

TableLayoutを使う
Button[] を12個配置する

point

TableLayoutのインスタンスに行インスタンス TableRowを追加
インスタンスにボタンを配置

TableLayout table = new TableLayout(context);
//forループ
TableRow row = new TableRow(context);  //TableRowインスタンス生成
row.addView(Buttonインスタンス)
table.addView(row) //TableRowインスタンスをTableLayoutインスタンスに配置

実行結果

f:id:donsuka_kk:20121118075325p:plain

Main.java

package com.example.l003_tablelayout;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class Main extends Activity {
	Context context;
	FrameLayout frame;
	LinearLayout linear;
	SurfaceView surface;
	View view;
	TextView tv_1;
	TextView tv_2;
	TableLayout table;
	
	final int WC = LinearLayout.LayoutParams.WRAP_CONTENT;
	final int FP = LinearLayout.LayoutParams.FILL_PARENT;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	
	    context = getApplicationContext();
	    frame = new FrameLayout(context);
	    setContentView(frame);
	    
	    //linear
	    linear = new LinearLayout(context);
	    linear.setOrientation(LinearLayout.VERTICAL);
	    frame.addView(linear);
	    
	    //tv_1
	    tv_1 = new TextView(context);
	    tv_1.setText("数学ゲーム");
	    //コンポーネントサイズの指定
	    tv_1.setLayoutParams(new LinearLayout.LayoutParams(FP,WC));
	    linear.addView(tv_1);
	    
	    //surface
	    surface = new SurfaceView(context);
	    linear.addView(surface,new LinearLayout.LayoutParams(FP,200));
	    
	    //view
	    view = new View(context);
	    linear.addView(view,new LinearLayout.LayoutParams(FP,200));
	    
	    //table
	    table = new TableLayout(context);
	    table.setBackgroundColor(Color.GRAY);
	    table.setLayoutParams(new LinearLayout.LayoutParams(FP,400));
	    linear.addView(table);
	    
	    Button[] table_buttons;
	    table_buttons = new Button[12];
	    int index = 0;
	    int value;
	    for(int iRow=0;iRow<4;iRow++){
	    	TableRow row = new TableRow(context);
	    	for(int iCol=0;iCol<3;iCol++){
	    		table_buttons[index] = new Button(context);
	    		
	    		row.addView(table_buttons[index]);
	    		LayoutParams params = (android.widget.LinearLayout.LayoutParams) table_buttons[index].getLayoutParams();
	    		params.width = 150;
	    		table_buttons[index].setLayoutParams(params);
	    		value = (index+1)%10;
	    		table_buttons[index].setText(""+value);
	    		index++;
	    	}
	    	table.addView(row);
	    }
	    
	    //tv_2
	    tv_2 = new TextView(context);
	    tv_2.setText("hoge");
	    linear.addView(tv_2);
	    
	}

}