這篇文章主要介紹了Android開發之計算器GridLayout佈局實現方法,結合實例形式分析了Android計算器界面佈局及表達式計算相關操作技巧,需要的朋友可以參考下
本文實例講述了Android開發之計算器GridLayout佈局實現方法。分享給大家供大家參考,具體如下:
運行效果:
Demo 下載地址:https://github.com/LonglyWolf/Calculator
或者點擊此處本站下載。
按鈕佈局實現:
一個Linearlayout 嵌套三個TextView 最下方的顯示當前計算式。上面爲先前的計算式。
Gridview 網格佈局排布按鈕
<?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:rowCount="7" android:columnCount="4" android:id="@+id/root" android:background="@color/buttonBackgroundBlack" android:padding="5dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_columnSpan="4"> <TextView android:id="@+id/textview_up" android:layout_width="match_parent" android:layout_height="60dp" android:layout_columnSpan="4" android:layout_gravity="right" android:background="#ff525252" android:padding="3pt" android:singleLine="true" android:gravity="right" android:textColor="#66ffffff" android:textSize="25sp" /> <TextView android:id="@+id/textview_down" android:layout_width="match_parent" android:layout_height="60dp" android:layout_columnSpan="4" android:layout_gravity="right" android:background="#ff525252" android:padding="3pt" android:singleLine="true" android:gravity="right" android:textColor="#66ffffff" android:textSize="25sp" /> <TextView android:id="@+id/textview" android:layout_width="match_parent" android:layout_height="75dp" android:layout_columnSpan="4" android:layout_gravity="right" android:background="#ff525252" android:padding="3pt" android:gravity="right" android:singleLine="true" android:textColor="#eee" android:textSize="40sp" android:maxLines="10"/> </LinearLayout> </GridLayout>
算法實現:
在這裏 我先將輸入的 中綴表達式,轉爲後綴表達式,再用後綴表達式進行了計算。
具體實現參照前面一篇:https://www.jb51.net/article/158331.htm
這裏給大家提供另一種更簡單的思路:
如果不要求算法,Java中已經自定義了:ScriptEngineManager類,我們可以直接調用它的方法,求得TextView上計算式的值
ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("nashorn"); String expression = tv.getText().toString; try { String result = String.valueOf(scriptEngine.eval(expression)); System.out.println(result); } catch (ScriptException e) { Toast.makeText(MainActivity.this,"請正確輸入",Toast.LENGTH_SHORT).show(); e.printStackTrace(); }
關於括號自動匹配:
設一個Flag,判斷前一個字符是什麼,空或者運算符就輸出“(”,然後falg++
否則輸出“)” falg-- 最後輸入完成,計算前直接檢查一下falg是否爲0即可:
最後講下原式的取回:
很多人計算的時候,會輸入錯誤,這是需要取回計算式
實現很簡單,一個點擊事件的事
比如說點完最頂上的TextView ,就把你當前的TextView.setText()就搞定了
具體算法實現可以參考我開頭給出的 Demo
更多關於Android相關內容感興趣的讀者可查看本站專題:《Android控件用法總結》、《Android開發入門與進階教程》、《Android視圖View技巧總結》、《Android編程之activity操作技巧總結》、《Android數據庫操作技巧總結》及《Android資源操作技巧彙總》
希望本文所述對大家Android程序設計有所幫助。