在现有源代码中创建新按钮?

时间:2013-03-03 18:17:56

标签: android eclipse button

http://www.itechcode.com/2012/03/18/create-calculator-in-android-programming/

我使用他的源代码,但它似乎与我用过的“初级水平”编程非常不同,即创建新项目,修改布局,在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;
    }
}

package com.pragmatouch.calculator;

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

1 个答案:

答案 0 :(得分: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。这将自动调整按钮的大小,使其平均显示在屏幕的宽度上。

  

我最好自己进行计算或修改现有代码吗?

我永远不会告诉别人重新创建方向盘,但是,如果你不能很好地理解代码以便在他们离开的地方拾取,那么这对你来说可能是一场艰难的挣扎。如果您无法理解提供给您的代码或如何修改代码,那么您最好的选择是将代码实际发布在另一个问题中并且非常具体,并询问我如何更改此特定按钮显示的内容以及单击它的结果将是。这个论坛取决于人们要求问题清晰简洁。如果没有,则问题将在打开时尽快结束。一般化在网站上受到严重谴责。

  

最后,我要做的是制作自己的科学计算器,但我不想花费额外的时间进行简单的操作。

回答这个问题的最佳方法是查看计算器在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;更改为{{1}},而您刚刚更改了它。所以理解代码需要一些时间,但你必须做一些试验和错误才能理解它。我希望这有助于回答你的问题。