1>GridLayout,4.0版本以上新增的网格布局,以下版本需要引用支撑包
package com.brady.est; import android.annotation.SuppressLint; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.widget.Button; import android.widget.GridLayout; import android.widget.GridLayout.LayoutParams; @SuppressLint("HandlerLeak") public class MainActivity extends ActionBarActivity { private String[] buttons={ "1","2","3","+", "4","5","6","-", "7","8","9","x", "0",".","/","="}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); GridLayout gridLayout = (GridLayout)findViewById(R.id.root); for(int i = 0 ;i<gridLayout.getRowCount()-2;i++){ //按键所在的单元格 行 //从第三行开始 GridLayout.Spec rowSpec = GridLayout.spec(i%gridLayout.getRowCount()+2); for(int j = 0;j<gridLayout.getColumnCount();j++){ Button button = new Button(this); button.setText(buttons[i*4+j]); button.setTextSize(40); //按键所在的单元格 列 GridLayout.Spec colSpec = GridLayout.spec(j%gridLayout.getColumnCount()); //该单元格布局 GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams(rowSpec, colSpec); layoutParams.setGravity(Gravity.FILL); //向网格组件 添加子组件button以及,该button的布局参数对象 gridLayout.addView(button, layoutParams); } } } @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; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
布局XML文件:
<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:columnCount="4" android:rowCount="6" android:id="@+id/root" tools:context="com.brady.est.MainActivity" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="0" android:layout_columnSpan="4"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_columnSpan="4" android:text="清除"/> </GridLayout>
界面:
时间: 2024-10-07 23:39:01