cn.nuc.calc包下MainActivity.java
package cn.nuc.calcu;
import cn.nuc.calcu.R.id;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.GridLayoutAnimationController;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.TextView;
import android.os.Build;
public class MainActivity extends Activity {
GridLayout gridLayout;
Button button;
TextView tView;
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.main);
gridLayout=(GridLayout) findViewById(R.id.root);
tView=(TextView) findViewById(R.id.text);
//button=(Button) findViewById(R.id.btn);
OnClickListener listener=new OnClickListener()
{
@Override
public void onClick(View arg0)
{
tView.setText("");
}
};
for (int i = 0; i < chars.length; i++)
{
button=new Button(this);
button.setText(chars[i]);
button.setTextSize(40);
//获取计算器按钮的行数
GridLayout.Spec rowSpec=GridLayout.spec(i/4+2);
//获取计算器按钮的列数
GridLayout.Spec coloumSpec=GridLayout.spec(i%4);
GridLayout.LayoutParams params=new GridLayout.LayoutParams(rowSpec,coloumSpec);
//使用组件填充父容器
params.setGravity(GridLayout.FIND_VIEWS_WITH_TEXT);
//params.setGravity(GridLayout.FILL);
gridLayout.addView(button, params);
}
//button按钮的监听事件
button.setOnClickListener(listener);
}
}
布局文件中main.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:columnCount="4"
android:rowCount="6"
android:id="@+id/root"
android:background="@drawable/bg"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:layout_columnSpan="4"
android:id="@+id/text"
android:background="#eee"
android:textColor="#000"
android:layout_gravity="right"
android:layout_marginLeft="4px"
android:layout_marginRight="4px"
android:padding="4px"
android:textSize="50sp"
/>
<!-- android:hint="数字显示" -->
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_columnSpan="4"
android:text="清除"
/>
</GridLayout>