2013-03-03 81 views
-1

http://www.itechcode.com/2012/03/18/create-calculator-in-android-programming/在現有源代碼中創建新按鈕?

進出口使用他的源代碼,但似乎比「初學者級別」編程我一直在使用IE瀏覽器創建新項目,修改佈局,main.java引用很大的不同,等

我試圖使用他的源代碼並修改/創建新操作並添加一個活動。如果不是以不同的方式佈置的話,我通常會知道如何去做大部分的事情。謝謝!

package com.pragmatouch.calculator; 

    import java.text.DecimalFormat; 
    import java.text.NumberFormat; 
    import java.util.Iterator; 
    import java.util.Stack; 

    import android.app.Activity; 
    import android.os.Bundle; 
    import android.widget.AdapterView; 
    import android.widget.Button; 
    import android.widget.TextView; 
    import android.widget.AdapterView.OnItemClickListener; 
    import android.widget.GridView; 
    import android.view.View; 
    import android.view.View.OnClickListener; 

    public class main extends Activity { 
     GridView mKeypadGrid; 
     TextView userInputText; 
     TextView memoryStatText; 

     Stack<String> mInputStack; 
     Stack<String> mOperationStack; 

     KeypadAdapter mKeypadAdapter; 
     TextView mStackText; 
     boolean resetInput = false; 
     boolean hasFinalResult = false; 

     String mDecimalSeperator; 
     double memoryValue = Double.NaN; 

     /** Called when the activity is first created. */ 
     @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 

      DecimalFormat currencyFormatter = (DecimalFormat) NumberFormat 
        .getInstance(); 
      char decimalSeperator = currencyFormatter.getDecimalFormatSymbols() 
        .getDecimalSeparator(); 
      mDecimalSeperator = Character.toString(decimalSeperator); 

      setContentView(R.layout.main); 

      // Create the stack 
      mInputStack = new Stack<String>(); 
      mOperationStack = new Stack<String>(); 

      // Get reference to the keypad button GridView 
      mKeypadGrid = (GridView) findViewById(R.id.grdButtons); 

      // Get reference to the user input TextView 
      userInputText = (TextView) findViewById(R.id.txtInput); 
      userInputText.setText("0"); 

      memoryStatText = (TextView) findViewById(R.id.txtMemory); 
      memoryStatText.setText(""); 

      mStackText = (TextView) findViewById(R.id.txtStack); 

      // Create Keypad Adapter 
      mKeypadAdapter = new KeypadAdapter(this); 

      // Set adapter of the keypad grid 
      mKeypadGrid.setAdapter(mKeypadAdapter); 

      // Set button click listener of the keypad adapter 
      mKeypadAdapter.setOnButtonClickListener(new OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        Button btn = (Button) v; 


        // Get the KeypadButton value which is used to identify the 
        // keypad button from the Button's tag 
        KeypadButton keypadButton = (KeypadButton) btn.getTag(); 

        // Process keypad button 
        ProcessKeypadInput(keypadButton); 
       } 
      }); 

      mKeypadGrid.setOnItemClickListener(new OnItemClickListener() { 
       public void onItemClick(AdapterView<?> parent, View v, 
         int position, long id) { 

       } 
      }); 

     } 

     private void ProcessKeypadInput(KeypadButton keypadButton) { 
      //Toast.makeText(this, keypadButton.getText(), Toast.LENGTH_SHORT).show(); 
      String text = keypadButton.getText().toString(); 
      String currentInput = userInputText.getText().toString(); 

      int currentInputLen = currentInput.length(); 
      String evalResult = null; 
      double userInputValue = Double.NaN; 

      switch (keypadButton) { 
      case BACKSPACE: // Handle backspace 
       // If has operand skip backspace 
       if (resetInput) 
        return; 

       int endIndex = currentInputLen - 1; 

       // There is one character at input so reset input to 0 
       if (endIndex < 1) { 
        userInputText.setText("0"); 
       } 
       // Trim last character of the input text 
       else { 
        userInputText.setText(currentInput.subSequence(0, endIndex)); 
       } 
       break; 
      case SIGN: // Handle -/+ sign 
       // input has text and is different than initial value 0 
       if (currentInputLen > 0 && currentInput != "0") { 
        // Already has (-) sign. Remove that sign 
        if (currentInput.charAt(0) == '-') { 
         userInputText.setText(currentInput.subSequence(1, 
           currentInputLen)); 
        } 
        // Prepend (-) sign 
        else { 
         userInputText.setText("-" + currentInput.toString()); 
        } 
       } 
       break; 
      case CE: // Handle clear input 
       userInputText.setText("0"); 
       break; 
      case C: // Handle clear input and stack 
       userInputText.setText("0"); 
       clearStacks(); 
       break; 
      case DECIMAL_SEP: // Handle decimal seperator 
       if (hasFinalResult || resetInput) { 
        userInputText.setText("0" + mDecimalSeperator); 
        hasFinalResult = false; 
        resetInput = false; 
       } else if (currentInput.contains(".")) 
        return; 
       else 
        userInputText.append(mDecimalSeperator); 
       break; 
      case DIV: 
      case PLUS: 
      case MINUS: 
      case MULTIPLY: 
       if (resetInput) { 
        mInputStack.pop(); 
        mOperationStack.pop(); 
       } else { 
        if (currentInput.charAt(0) == '-') { 
         mInputStack.add("(" + currentInput + ")"); 
        } else { 
         mInputStack.add(currentInput); 
        } 
        mOperationStack.add(currentInput); 
       } 

       mInputStack.add(text); 
       mOperationStack.add(text); 

       dumpInputStack(); 
       evalResult = evaluateResult(false); 
       if (evalResult != null) 
        userInputText.setText(evalResult); 

       resetInput = true; 
       break; 
      case CALCULATE: 
       if (mOperationStack.size() == 0) 
        break; 

       mOperationStack.add(currentInput); 
       evalResult = evaluateResult(true); 
       if (evalResult != null) { 
        clearStacks(); 
        userInputText.setText(evalResult); 
        resetInput = false; 
        hasFinalResult = true; 
       } 
       break; 
      case M_ADD: // Add user input value to memory buffer 
       userInputValue = tryParseUserInput(); 
       if (Double.isNaN(userInputValue)) 
        return; 
       if (Double.isNaN(memoryValue)) 
        memoryValue = 0; 
       memoryValue += userInputValue; 
       displayMemoryStat(); 

       hasFinalResult = true; 

       break; 
      case M_REMOVE: // Subtract user input value to memory buffer 
       userInputValue = tryParseUserInput(); 
       if (Double.isNaN(userInputValue)) 
        return; 
       if (Double.isNaN(memoryValue)) 
        memoryValue = 0; 
       memoryValue -= userInputValue; 
       displayMemoryStat(); 
       hasFinalResult = true; 
       break; 
      case MC: // Reset memory buffer to 0 
       memoryValue = Double.NaN; 
       displayMemoryStat(); 
       break; 
      case MR: // Read memoryBuffer value 
       if (Double.isNaN(memoryValue)) 
        return; 
       userInputText.setText(doubleToString(memoryValue)); 
       displayMemoryStat(); 
       break; 
      case MS: // Set memoryBuffer value to user input 
       userInputValue = tryParseUserInput(); 
       if (Double.isNaN(userInputValue)) 
        return; 
       memoryValue = userInputValue; 
       displayMemoryStat(); 
       hasFinalResult = true; 
       break; 
      case PRGM: 
      break; 
      default: 
       if (Character.isDigit(text.charAt(0))) { 
        if (currentInput.equals("0") || resetInput || hasFinalResult) { 
         userInputText.setText(text); 
         resetInput = false; 
         hasFinalResult = false; 
        } else { 
         userInputText.append(text); 
         resetInput = false; 
        } 

       } 
       break; 

      } 

     } 

     private void clearStacks() { 
      mInputStack.clear(); 
      mOperationStack.clear(); 
      mStackText.setText(""); 
     } 

     private void dumpInputStack() { 
      Iterator<String> it = mInputStack.iterator(); 
      StringBuilder sb = new StringBuilder(); 

      while (it.hasNext()) { 
       CharSequence iValue = it.next(); 
       sb.append(iValue); 

      } 

      mStackText.setText(sb.toString()); 
     } 

     private String evaluateResult(boolean requestedByUser) { 
      if ((!requestedByUser && mOperationStack.size() != 4) 
        || (requestedByUser && mOperationStack.size() != 3)) 
       return null; 

      String left = mOperationStack.get(0); 
      String operator = mOperationStack.get(1); 
      String right = mOperationStack.get(2); 
      String tmp = null; 
      if (!requestedByUser) 
       tmp = mOperationStack.get(3); 

      double leftVal = Double.parseDouble(left.toString()); 
      double rightVal = Double.parseDouble(right.toString()); 
      double result = Double.NaN; 

      if (operator.equals(KeypadButton.DIV.getText())) { 
       result = leftVal/rightVal; 
      } else if (operator.equals(KeypadButton.MULTIPLY.getText())) { 
       result = leftVal * rightVal; 

      } else if (operator.equals(KeypadButton.PLUS.getText())) { 
       result = leftVal + rightVal; 
      } else if (operator.equals(KeypadButton.MINUS.getText())) { 
       result = leftVal - rightVal; 

      } 

      String resultStr = doubleToString(result); 
      if (resultStr == null) 
       return null; 

      mOperationStack.clear(); 
      if (!requestedByUser) { 
       mOperationStack.add(resultStr); 
       mOperationStack.add(tmp); 
      } 

      return resultStr; 
     } 

     private String doubleToString(double value) { 
      if (Double.isNaN(value)) 
       return null; 

      long longVal = (long) value; 
      if (longVal == value) 
       return Long.toString(longVal); 
      else 
       return Double.toString(value); 

     } 

     private double tryParseUserInput() { 
      String inputStr = userInputText.getText().toString(); 
      double result = Double.NaN; 
      try { 
       result = Double.parseDouble(inputStr); 

      } catch (NumberFormatException nfe) { 
      } 
      return result; 

     } 

     private void displayMemoryStat() { 
      if (Double.isNaN(memoryValue)) { 
       memoryStatText.setText(""); 
      } else { 
       memoryStatText.setText("M = " + doubleToString(memoryValue)); 
      } 
     } 

    } 

ENUM:

package com.pragmatouch.calculator; 

public enum KeypadButton { 
    MC("MC",KeypadButtonCategory.MEMORYBUFFER) 
    , MR("MR",KeypadButtonCategory.MEMORYBUFFER) 
    , MS("MS",KeypadButtonCategory.MEMORYBUFFER) 
    , M_ADD("M+",KeypadButtonCategory.MEMORYBUFFER) 
    , M_REMOVE("M-",KeypadButtonCategory.MEMORYBUFFER) 
    , BACKSPACE("<-",KeypadButtonCategory.CLEAR) 
    , CE("CE",KeypadButtonCategory.CLEAR) 
    , C("C",KeypadButtonCategory.CLEAR) 
    , ZERO("0",KeypadButtonCategory.NUMBER) 
    , ONE("1",KeypadButtonCategory.NUMBER) 
    , TWO("2",KeypadButtonCategory.NUMBER) 
    , THREE("3",KeypadButtonCategory.NUMBER) 
    , FOUR("4",KeypadButtonCategory.NUMBER) 
    , FIVE("5",KeypadButtonCategory.NUMBER) 
    , SIX("6",KeypadButtonCategory.NUMBER) 
    , SEVEN("7",KeypadButtonCategory.NUMBER) 
    , EIGHT("8",KeypadButtonCategory.NUMBER) 
    , NINE("9",KeypadButtonCategory.NUMBER) 
    , PLUS(" + ",KeypadButtonCategory.OPERATOR) 
    , MINUS(" - ",KeypadButtonCategory.OPERATOR) 
    , MULTIPLY(" * ",KeypadButtonCategory.OPERATOR) 
    , DIV("/",KeypadButtonCategory.OPERATOR) 
    , RECIPROC("1/x",KeypadButtonCategory.OTHER) 
    , DECIMAL_SEP(",",KeypadButtonCategory.OTHER) 
    , SIGN("±",KeypadButtonCategory.OTHER) 
    , SQRT("SQRT",KeypadButtonCategory.OTHER) 
    , PERCENT("%",KeypadButtonCategory.OTHER) 
    , CALCULATE("=",KeypadButtonCategory.RESULT) 
    , PRGM("PRGM",KeypadButtonCategory.PRGM) 
    , DUMMY("",KeypadButtonCategory.DUMMY); 

    CharSequence mText; // Display Text 
    KeypadButtonCategory mCategory; 

    KeypadButton(CharSequence text,KeypadButtonCategory category) { 
     mText = text; 
     mCategory = category; 
    } 

    public CharSequence getText() { 
     return mText; 
    } 
} 

包com.pragmatouch.calculator;

public enum KeypadButtonCategory { 
    MEMORYBUFFER 
    , NUMBER 
    , OPERATOR 
    , DUMMY 
    , CLEAR 
    , RESULT 
    , OTHER 
    , PRGM 
} 
+0

你想要做什麼?添加一個新的按鈕到佈局?爲什麼不能通過'layout.xml'做到這一點? – Swayam 2013-03-03 18:25:09

+0

我正在投票結束此事,因爲你沒有提出明確的問題。嘗試改寫,以便我們知道你想要做什麼。只需創建一個按鈕就像新的Button()一樣簡單,然後將其添加到佈局。但我不認爲這真的是你想知道的。 – 2013-03-03 18:26:33

+0

我想在自己的喜好中添加/修改gridview中的按鈕,但我並不完全熟悉枚舉,適配器等。所以我希望有人能夠簡單地回答如何添加按鈕,修改它們的大小等。感謝您的時間! – user2077705 2013-03-03 18:32:13

回答

1

我對你有一個很好的答案。我最近想在android中創建自己的按鈕,但我想以簡單的方式完成。按照這些步驟,幾分鐘後我會發布圖片。

1)創建一個新的佈局。從LinearLayout開始。在其中嵌入FramedLayout和另一個LinearLayout

2)然後添加一個TextView它。這是練習完美的地方。玩弄屬性。瞭解他們做什麼。當您有關於如何顯示按鈕的一般信息時,請轉至下一步。 3)你要做什麼是在另一個視圖中包含這個作爲按鈕。你可以使用一個特定的屬性來使它看起來像一個按鈕。

給我幾分鐘,我會張貼一些代碼和圖片。

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/CBN_LinearLayout" 
style="@android:style/Widget.Button" 
android:layout_width="match_parent" 
android:layout_height="50dp" 
android:orientation="vertical" > 

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 

    <TextView 
     android:id="@+id/CBV_texview1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center_vertical" 
     android:layout_marginRight="10dp" 
     android:layout_weight="1" 
     android:gravity="right" 
     android:text="@string/checkorder" 
     android:textColor="@color/Black" /> 

    <FrameLayout 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center_vertical" 
     android:layout_weight="1" > 

     <ImageView 
      android:id="@+id/CBV_imageView1" 
      android:layout_width="23dp" 
      android:layout_height="15dp" 
      android:layout_gravity="center_vertical" 
      android:contentDescription="@string/redcirclenotify" 
      android:src="@drawable/rednotify" 
      android:visibility="visible" /> 

     <TextView 
      android:id="@+id/CBV_textview2" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center_vertical" 
      android:layout_marginLeft="8dp" 
      android:gravity="left" 
      android:text="@string/zero" 
      android:visibility="visible" /> 

    </FrameLayout> 
</LinearLayout> 

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" > 

    <TextView 
     android:id="@+id/CBV_textview3" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_weight="1" 
     android:fadingEdge="horizontal" 
     android:gravity="center_horizontal" 
     android:text="@string/blankstring" /> 

    <TextView 
     android:id="@+id/CBV_textview4" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_weight="1" 
     android:gravity="center_horizontal" 
     android:text="@string/blankstring" /> 
</LinearLayout> 

,當你將它添加到其他視圖,你使用一個按鈕:

<include 
     android:id="@+id/MI_checkorder" 
     style="android:buttonStyle" 
     android:layout_width="wrap_content" 
     android:layout_height="50dp" 
     android:layout_gravity="bottom" 
     android:layout_marginTop="5dp" 
     android:layout_weight="1" 
     layout="@layout/custombtnview" 
     android:background="@style/AppTheme" 
     android:clickable="true" 
     android:focusable="true" /> 

這樣做的重要組成部分,是設置樣式爲根LinearLayout@android:style/Widget.Button

一旦完成,它會看起來像一個按鈕,像按鈕一樣工作。

下面是最終產品的圖像:

Custom Android Button http://i45.tinypic.com/5y9nac.jpg

你的問題的另一部分。在Android中調整標準按鈕的大小:

1)幾乎所有東西都可以通過使用XML的方式進行控制。這些都可以在ADK的該區域進行控制。這些屬性可幫助您控制幾乎所有方面。

例如在計算器...

你有一排4個按鍵,所以你要添加一個水平LinearLayout內4個按鈕。然後,您可以給每個按鈕1的權重,然後將它們的Width設置爲FillParent。這將自動調整按鈕的大小,以平均顯示在屏幕的寬度上。

我是否更適合自己的calc或修改現有的代碼?

我永遠不會告訴別人重新創建輪子,但是,如果您不能很好地理解代碼,以便它們停止運行,那麼這對您來說可能是一場艱苦的鬥爭。如果您無法理解給予您的代碼或者如何修改代碼,那麼最好的辦法是實際上將代碼發佈到另一個問題中,並且要非常具體,並要求我舉例說明如何更改此特定按鈕的顯示內容以及點擊它的結果是。這個論壇取決於人們提出的問題要簡潔明瞭。如果不是這樣,那麼問題就會以打開的速度結束。網站上泛化現象嚴重。

最後,我試圖做的是讓自己的科學計算器,但我不想花費額外的時間做簡單的操作。

回答此問題的最佳方法是查看計算器在GUI或圖形佈局中的組裝方式。嘗試改變一個按鈕,它做了什麼。例如,將加號減去僅用於學習曲線。

1)尋找, PLUS(" + ",KeypadButtonCategory.OPERATOR)並注意這是一個加號字符串。將其更改爲「T」,看看它是否在應用程序中發生變化。如果確實如此,那麼進入代碼。在代碼中,您會找到case CALCULATE:代表ENUM中的=號,然後在裏面找到evalResult = evaluateResult(true);。如果按照這個你達到:

if (operator.equals(KeypadButton.DIV.getText())) { 
      result = leftVal/rightVal; 
     } else if (operator.equals(KeypadButton.MULTIPLY.getText())) { 
      result = leftVal * rightVal; 

     } else if (operator.equals(KeypadButton.PLUS.getText())) { 
      result = leftVal + rightVal; 
     } else if (operator.equals(KeypadButton.MINUS.getText())) { 
      result = leftVal - rightVal; 

     } 

所以現在你可以改變result = leftVal + rightVal;result = leftVal - rightVal;和你剛纔改變了它。所以需要一些時間來理解代碼,但是你必須做一些試驗和錯誤來理解它。我希望這有助於回答你的問題。

+0

我明白如何做這樣的事情,但我的問題在於編輯此代碼: – user2077705 2013-03-03 18:42:07

+0

解釋你的意思是編輯和你的意思是代碼(我的代碼?) – Mark 2013-03-03 18:45:42

+0

此代碼:http://www.itechcode.com/2012/03/18 /創建計算器在Android編程/ – user2077705 2013-03-03 18:48:59