Android中GridLayout布局

GridLayout布局,实现计算机界面:

<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:rowCount="6"
    android:columnCount="4"
    android:id="@+id/root"
   >
   <!-- 定义一个横跨四列的文本框,并设置文本框的前景色、背景色等属性 -->
   <EditText 
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_columnSpan="4"
       android:textSize="50sp"
       android:layout_marginLeft="4px"
       android:layout_marginRight="4px"
       android:padding="5px"
       android:layout_gravity="right"
       android:background="#eee"
       android:textColor="#000"
       android:text="0"
       />
   <Button 
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_columnSpan="4"
       android:text="清除"
       />
</GridLayout>



Activity

	GridLayout gridLayout;
	//定义16个按钮的文本
	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) findViewById(R.id.root);
		for(int i=0;i<chars.length;i++){
			Button bn=new Button(this);
			bn.setText(chars[i]);
			//设置按钮的字体大小
			bn.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);
			gridLayout.addView(bn,params);
		}
	}




















你可能感兴趣的:(计算器界面)