Android 的计算器界面设计

来源:互联网 发布:债券代持 知乎 编辑:程序博客网 时间:2024/06/12 04:26

第一步:在Main_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:rowCount="6"    android:columnCount="4"    android:id="@+id/root"    >    <TextView android:text="0"        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"        />    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_columnSpan="4"        android:text="清除"/></GridLayout>
第二步,在MainActivity中的代码:
package com.example.yangjian.learngridlayout;import android.support.v7.app.ActionBarActivity;import android.os.Bundle;import android.view.Gravity;import android.view.Menu;import android.view.MenuItem;import android.widget.Button;import android.widget.GridLayout;public class MainActivity extends ActionBarActivity {    GridLayout gridLayout;    String[] chars = new String[]{            "7", "8", "9", "÷",            "4", "5", "6", "×",            "3", "2", "1", "-",            ".", "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);        }    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.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();        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }}

0 0