安卓實現簡單版計算器——移動端課程學習開發日誌
佈局如圖:
實現步驟:
新建一個空活動的項目
這裏建立一個空活動的項目就好
編寫佈局
這裏我們整體的佈局使用Linear Layout佈局,顯示區使用Text View,計算器的按鈕區域使用Grid Layout佈局,裏面的數字使用Button空間,並且爲各個按鈕和TextView添加id
xml關鍵代碼(省略很多)
<LinearLayout>
<!-- 顯示結果區域,文本標籤 -->
<LinearLayout>
<TextView></TextView>
</LinearLayout>
<LinearLayout>
<!-- 清除按鈕,清空輸入和結果,歸零 -->
<Button />
<!-- 刪除按鈕,刪除上一個輸入 -->
<Button />
</LinearLayout>
<!-- 網格佈局,設置4行4列 -->
<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:rowCount="4"
android:columnCount="4"
>
<!-- 按鈕1-9,放置1-9的數字按鈕,+-*/等各種操作符 -->
<Buton />
</GridLayout>
</LinearLayout>
獲取視圖的各種按鈕的實例,建立監聽函數
在MainActivity類中進行邏輯操作
-
繼承父類
super.onCreate(savedInstanceState);
-
設置佈局layout
setContentView(R.layout.activity_main);
-
獲取各種數字按鈕、操作符按鈕、結果顯示區域的實例(
findViewById(R.id.xxx)
) -
設置實例的監聽器監聽點擊了按鈕之後執行相應的操作,比如,輸出運算結果,將點擊的按鈕數字輸出到顯示區
-
編寫update方法,更新結果顯示區內容
//遍歷集合 轉化爲String類型方便顯示
String str = "";
for(char c : strs){
str +=c;
}
//str!=''是因爲Double.valueof不是轉化“”這個字符串
if (x=='0'&&str!="") {
textView.setText(str);
current = Double.valueOf(str);
}
//第一次輸入的賦值,不這樣做下面的last = sum 會產生錯誤結果
if (isFirst){sum = current;}
//進行符號判斷並在textview顯示符號
if (x == '-'){
textView.setText("-");
strs = new ArrayList<>();isFirst = false;
}else if (x == '+'){
textView.setText("+");
strs = new ArrayList<>();isFirst = false;
}else if (x == '×'){
textView.setText("×");
strs = new ArrayList<>();isFirst = false;
}else if (x == '÷'){
textView.setText("÷");
strs = new ArrayList<>();isFirst = false;
}
/**
* lastChar!=‘1’是爲了保證在獲得符號才進入計算
* isYuansuan 比如要輸入11x11 這個運算 因爲我們這個函數是每次輸入一個char(數字)就會更新一次,我們希望
* 不會再輸入到11x1 的時候 就進入這個運算判斷,而是等到我們輸入到11x11 後面再接一個符號才運算,
* isYunsuan也是在這個時候爲true的,這樣才能保證運算正確
*/
if (lastChar!='1'&&isYunsuan&&x!='0'){
//計算值
if (lastChar=='-'){
sum = last - current;
}else if (lastChar=='+'){
sum = last + current;
}else if (lastChar=='×'){
sum = (last * current);
}else if (lastChar=='÷'){
sum = (last / current);
}
isYunsuan = false;//運算完成後置位false
}
last = sum;//保存當前計算結果到last 用於下一次的計算
if (x!='0') {
lastChar = x;
isYunsuan = true;
}
//當按‘=’的時候,進行輸出結果
if (x=='='){
textView.setText(sum+"");
lastChar = '1';
strs = new ArrayList<>();
}
}
編寫監聽函數的邏輯,實現計算功能,並輸出到顯示區(TextView)中
點擊數字時:
-
更新存儲的字符串;
-
調用update方法;
點擊±*/操作符時
調用updateView方法