項目實戰:實現一個簡單計算器android
界面設計算法
(1)拖進一個大文本,整屏,設計各個數字及運算,用Table來存放。數組
<TableLayoutapp
android:layout_width="fill_parent"ide
android:layout_height="wrap_content">this
<TableRowspa
android:id="@+id/tableRow1"設計
android:layout_width="fill_parent"orm
android:layout_height="wrap_content">ci
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="1"></Button>
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="2"></Button
(2)實現算法,一個數字一個操做符號,執行第二個操做符號時前面就運算,有三項就執行運算,用數組記錄,建立種類類:
publicclass Types {
publicstaticfinalintADD = 1;
publicstaticfinalintSUB = 2;
publicstaticfinalintX = 3;
publicstaticfinalintDIV = 4;
publicstaticfinalintNUM = 5;
}
(3)存入數字或符號,項類
publicclass Item {
public Item(double value,int type){
this.value=value;
this.type=type;
}
publicdoublevalue=0;
publicinttype=0;
}
(4)定義數組,存放內容爲Item
private List<Item>items = new ArrayList<Item>();
(5) 若是輸入數字,直接添加:
publicvoid onClick(View v) {
switch (v.getId()) {
case R.id.btn0:
tvScreen.append("0");
break;
case R.id.btn1:
tvScreen.append("1");
break;
case R.id.btn2:
tvScreen.append("2");
break;
。。。。。
(6)實現相加
case R.id.btnAdd:
items.add(new Item(Double.parseDouble(tvScreen.getText().toString()),Types.NUM));
判斷是否有三項了,寫成一個方法:
checkAndCompute();
實現:
publicvoid checkAndCompute(){
if (items.size()>=3) {
double a = items.get(0).value;
double b = items.get(2).value;
int opt = items.get(1).type;
items.clear();
switch (opt) {
case Types.ADD:
items.add(new Item(a+b, Types.NUM));
break;
case Types.SUB:
items.add(new Item(a-b, Types.NUM));
break;
case Types.X:
items.add(new Item(a*b, Types.NUM));
break;
case Types.DIV:
items.add(new Item(a/b, Types.NUM));
break;
}
}
}
(7)結構保存,而且屏幕清空
items.add(new Item(0, Types.ADD));
tvScreen.setText("");
break;
(8)實現減等其它運算
case R.id.btnSub:
items.add(new Item(Double.parseDouble(tvScreen.getText().toString()),InputTypes.NUM));
checkAndCompute();
items.add(new Item(0, InputTypes.SUB));
tvScreen.setText("");
break;
(9)實現等於號等運算
case R.id.btnResult:
items.add(new Item(Double.parseDouble(tvScreen.getText().toString()),InputTypes.NUM));
checkAndCompute();
tvScreen.setText(items.get(0).value+"");
items.clear();
break;