最近在做一个计算器小demo,中间真是踩了不少坑
,所以打算系统的总结一下,也不枉我耗费了这么多心血。
计算器要求如下图所示,要求可以进行简单的加减乘除运算,按下clear按钮清空上面的表达式。

一、界面设计
上面是一个EditText用来表示输入框
下面键盘设计是GridView
代码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView
android:id="@+id/grid_buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="4"
android:layout_margin="10dip"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:gravity="center"
android:layout_alignParentBottom="true"
>
</GridView>
<EditText
android:id="@+id/edit_input"
android:padding="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:singleLine="false"
android:hint="@string/hint_text"
android:editable="false"
android:textSize="22sp"
android:layout_above="@id/grid_buttons"
android:layout_alignParentTop="true"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:gravity="start"/>
</RelativeLayout>
</LinearLayout>
然后用一个适配器给键盘上的数字赋值:
//按钮中的字符
private final String[] buttons = new String[]{
"9", "8", "7", "+",
"6", "5", "4", "-",
"3", "2", "1", "x",
"0", "clear", "=", "/",
};
<