GridLayout

android 4.0提供了表格布局组件

xml

<?xml version="1.0" encoding="utf-8" ?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:rowCount="6"
    android:columnCount="4"
    android:id="@+id/root">
    
	<!-- 定义一个横跨4列的文本框 -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_columnSpan="4"
        android:textSize="50sp"
        android:layout_marginLeft="4dip"
        android:layout_marginRight="4dip"
        android:padding="5dip"
        android:layout_gravity="right"
        android:background="#eee"
        android:textColor="#000"
        android:text="0"></TextView>
	<Button
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content"
	    android:layout_columnSpan="4"
	    android:text="clear"></Button>
</GridLayout>

  java

package com.frank.gridlayoutmanage;

import android.os.Bundle;
import android.app.Activity;
import android.view.Gravity;
import android.view.Menu;
import android.widget.*;

public class MainActivity extends Activity {
	GridLayout gridLayout;
	//创建计算器按钮
	String[] chars = new String[]{
			"7","8","9","/",
			"4","5","6","*",
			"1","2","3","-",
			".","0","=","+"
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		//获得布局组件
		gridLayout = (GridLayout)super.findViewById(R.id.root);
		for(int i = 0;i<chars.length;i++)
		{
			Button btn = new Button(this);//定义按钮
			btn.setText(chars[i]);//设置显示文字
			btn.setTextSize(40);//设置字体
			//指定组件所在的行
			GridLayout.Spec rowSpec = GridLayout.spec(i/4+2);
			//指定组件所在的列
			GridLayout.Spec columnSpec = GridLayout.spec(i%4);
			//把行和列放入布局参数对象里面
			GridLayout.LayoutParams params = new GridLayout.LayoutParams(
					rowSpec,columnSpec);
			//设置该组件占满容器
			params.setGravity(Gravity.FILL);
			//把btn放入布局参数对象里面所在的行和列
			gridLayout.addView(btn,params);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

  

posted on 2013-10-31 16:57  wp456  阅读(559)  评论(0)    收藏  举报

导航