【问题标题】:Android app - Inputting integers from buttons depending on number of pressesAndroid 应用程序 - 根据按下次数从按钮输入整数
【发布时间】:2017-02-07 18:48:56
【问题描述】:

我正在使用 android studio 为 android 编写一个计算器应用程序。我想使用 4 个按钮来输入值和功能。然而,我目前的做法是从按钮上写的文本中获取输入。因此,对于我的按钮 1/2/3,当它被按下时,1/2/3 被传递给 textView。

下面是我的 MainActivity:

   package com.example.myfirstapp;

import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.MediaController;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity  {
    private int[] operatorButtons = {R.id.operators};
    private int[] numericButtons = {R.id.onetwothree, R.id.fourfivesix, R.id.seveneightninezero};
    private boolean  lastNumeric, stateError;
    private TextView txtScreen;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Find the TextView
        this.txtScreen = (TextView) findViewById(R.id.txtScreen);
        // Find and set OnClickListener to numeric buttons
        setNumericOnClickListener();
        // Find and set OnClickListener to operator buttons, equal button and decimal point button
        setOperatorOnClickListener();
    }


    private void setNumericOnClickListener() {
        // Create a common OnClickListener
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Just append/set the text of clicked button
                Button button = (Button) v;
                if (stateError) {
                    // If current state is Error, replace the error message
                    txtScreen.setText(button.getText());
                    stateError = false;
                } else {
                    // If not, already there is a valid expression so append to it
                    txtScreen.append(button.getText());
                }
                // Set the flag
                lastNumeric = true;
            }
        };
        // Assign the listener to all the numeric buttons
        for (int id : numericButtons) {
            findViewById(id).setOnClickListener(listener);
        }
    }

    private void setOperatorOnClickListener() {
        // Create a common OnClickListener for operators
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // If the current state is Error do not append the operator
                // If the last input is number only, append the operator
                if (lastNumeric && !stateError) {
                    Button button = (Button) v;
                    txtScreen.append(button.getText());
                    lastNumeric = false;

                }
            }
        };
        // Assign the listener to all the operator buttons
        for (int id : operatorButtons) {
            findViewById(id).setOnClickListener(listener);
        }


        // Equal button
        /*findViewById(R.id.btnEqual).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onEqual();
            }
        });*/
    }
}

还有我的activity_main:

  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/txtScreen"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:gravity="right|center_vertical"
        android:maxLength="16"
        android:padding="10dp"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="30sp"
        android:typeface="serif" />
   <!--<Button-->
        <!--android:id="@+id/equal1"-->
        <!--android:layout_width="match_parent"-->
        <!--android:layout_height="100dp"-->
        <!--android:text="="-->
         <!--/>-->

    <Button
        android:id="@+id/equal2"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:text="="
        android:layout_alignParentBottom="true"
         />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/txtScreen"
        android:orientation="vertical"
        android:layout_above="@id/equal2">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1">

            <Button
                android:id="@+id/onetwothree"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:text="1/2/3"/>

            <Button
                android:id="@+id/fourfivesix"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:text="4/5/6"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1">

            <Button
                android:id="@+id/seveneightninezero"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:text="7/8/9/0"/>

            <Button
                android:id="@+id/operators"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:text="+-*/"/>

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>

例如,我是否可以从我的第一个按钮获得 1、2 或 3 的输入?所以按 1 次得到 1,按 2 次得到 2,以此类推。

非常感谢任何有关我如何继续前进的建议/想法。

亲切的问候, 本

【问题讨论】:

    标签: java android button


    【解决方案1】:

    您可以使用计时器或延迟变量来检测单击、双击或三击。这个post 可能很有趣。如果时间间隔不是一个因素,您可以只跟踪最后一次按下的按钮,如果再次按下相同的按钮,则相应地更新文本。

    如果您遵循方法一,按钮onetwothree 的点击侦听器的代码可能是这样的(我注释掉了setNumericOnClickListener()setOperatorOnClickListener();在mainActivity onCreate 中添加了以下内容):

    Button onetwothree = (Button) findViewById(R.id.onetwothree);
        onetwothree.setOnTouchListener(new View.OnTouchListener() {
    
            Handler handler = new Handler();
    
            int numberOfTaps = 0;
            long lastTapTimeMs = 0;
            long touchDownMs = 0;
    
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        touchDownMs = System.currentTimeMillis();
                        break;
                    case MotionEvent.ACTION_UP:
                        handler.removeCallbacksAndMessages(null);
                        if ((System.currentTimeMillis() - touchDownMs) > ViewConfiguration.getTapTimeout()) {
                            //it was not a tap
    
                            numberOfTaps = 0;
                            lastTapTimeMs = 0;
                            break;
                        }
    
                        if (numberOfTaps > 0
                                && (System.currentTimeMillis() - lastTapTimeMs) < ViewConfiguration.getDoubleTapTimeout()) {
                            numberOfTaps += 1;
                        } else {
                            numberOfTaps = 1;
                        }
                        lastTapTimeMs = System.currentTimeMillis();
    
                        if (numberOfTaps == 1) {
                            handler.postDelayed(new Runnable() {
    
                                @Override
                                public void run() {
                                    if (txtScreen.getText().toString() == "") {
                                        txtScreen.setText("1");
                                    } else txtScreen.append("1");
                                }
                            }, ViewConfiguration.getDoubleTapTimeout());
    
    
    
                        }else if (numberOfTaps == 2) {
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    if (txtScreen.getText().toString() == "") {
                                        txtScreen.setText("2");
                                    } else txtScreen.append("2");
                                }
                            }, ViewConfiguration.getDoubleTapTimeout());
    
                        } else if (numberOfTaps == 3) {
                                    if (txtScreen.getText().toString() == "") {
                                        txtScreen.setText("3");
                                    } else txtScreen.append("3");
                        }
                }
    
                return true;
            }
        });
    

    完成 MainActivity:

    package com.example.myfirstapp;
    
    import android.os.Bundle;
    import android.os.Handler;
    import android.support.v7.app.ActionBarActivity;
    import android.view.MotionEvent;
    import android.view.View;
    import android.view.ViewConfiguration;
    import android.widget.Button;
    import android.widget.TextView;
    
    public class MainActivity extends ActionBarActivity  {
        private int[] operatorButtons = {R.id.operators};
        private int[] numericButtons = {R.id.onetwothree, R.id.fourfivesix, R.id.seveneightninezero};
        private boolean  lastNumeric, stateError;
        private TextView txtScreen;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Find the TextView
        this.txtScreen = (TextView) findViewById(R.id.txtScreen);
        // Find and set OnClickListener to numeric buttons
    //        setNumericOnClickListener();
            // Find and set OnClickListener to operator buttons, equal button and decimal point button
    //        setOperatorOnClickListener();
    
        Button onetwothree = (Button) findViewById(R.id.onetwothree);
        onetwothree.setOnTouchListener(new View.OnTouchListener() {
    
            Handler handler = new Handler();
    
            int numberOfTaps = 0;
            long lastTapTimeMs = 0;
            long touchDownMs = 0;
    
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        touchDownMs = System.currentTimeMillis();
                        break;
                    case MotionEvent.ACTION_UP:
                        handler.removeCallbacksAndMessages(null);
                        if ((System.currentTimeMillis() - touchDownMs) > ViewConfiguration.getTapTimeout()) {
                            //it was not a tap
    
                            numberOfTaps = 0;
                            lastTapTimeMs = 0;
                            break;
                        }
    
                        if (numberOfTaps > 0
                                && (System.currentTimeMillis() - lastTapTimeMs) < ViewConfiguration.getDoubleTapTimeout()) {
                            numberOfTaps += 1;
                        } else {
                            numberOfTaps = 1;
                        }
                        lastTapTimeMs = System.currentTimeMillis();
    
                        if (numberOfTaps == 1) {
                            handler.postDelayed(new Runnable() {
    
                                @Override
                                public void run() {
                                    if (txtScreen.getText().toString() == "") {
                                        txtScreen.setText("1");
                                    } else txtScreen.append("1");
                                }
                            }, ViewConfiguration.getDoubleTapTimeout());
    
    
    
                        }else if (numberOfTaps == 2) {
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    if (txtScreen.getText().toString() == "") {
                                        txtScreen.setText("2");
                                    } else txtScreen.append("2");
                                }
                            }, ViewConfiguration.getDoubleTapTimeout());
    
                        } else if (numberOfTaps == 3) {
                                    if (txtScreen.getText().toString() == "") {
                                        txtScreen.setText("3");
                                    } else txtScreen.append("3");
                        }
                }
    
                return false;
            }
        });
    }
    
    
    private void setNumericOnClickListener() {
        // Create a common OnClickListener
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Just append/set the text of clicked button
                Button button = (Button) v;
                if (stateError) {
                    // If current state is Error, replace the error message
                    txtScreen.setText(button.getText());
                    stateError = false;
                } else {
                    // If not, already there is a valid expression so append to it
                    txtScreen.append(button.getText());
                }
                // Set the flag
                lastNumeric = true;
            }
        };
        // Assign the listener to all the numeric buttons
        for (int id : numericButtons) {
            findViewById(id).setOnClickListener(listener);
        }
    }
    
    private void setOperatorOnClickListener() {
        // Create a common OnClickListener for operators
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // If the current state is Error do not append the operator
                // If the last input is number only, append the operator
                if (lastNumeric && !stateError) {
                    Button button = (Button) v;
                    txtScreen.append(button.getText());
                    lastNumeric = false;
    
                }
            }
        };
        // Assign the listener to all the operator buttons
        for (int id : operatorButtons) {
            findViewById(id).setOnClickListener(listener);
        }
    
    
    }
    }
    

    【讨论】:

    • 稍微更改了答案,并添加了单击、双击和三次单击的示例代码。
    • 嗨,看看那个代码,它看起来就像我想要的那样。当尝试在我的代码中使用它时,我收到有关 viewConfiguration 和 setOnTouch 侦听器和事件等的错误。我知道这是一个愚蠢的问题,但我需要导入一些东西来使用这些吗?我是 android studio 和 android 开发的新手。感谢您的帮助
    • 嗨,我将所有导入的 mainActivity 添加到我的答案中以进一步澄清。您还可以在 Android Studio 中打开自动导入。首选项>编辑器>常规>自动导入,然后选中包括Add unambiguous imports on the fly的框。
    • 另外,您遇到了什么样的错误?如果您可以从 logcat 中提及错误会更容易。让我知道进口是否解决了问题:)
    • 您好,感谢您提供有关汽车进口的提示!这会为我省去很多悲伤。该解决方案完美运行,我现在可以实现其他按钮。
    【解决方案2】:

    做一些操作时可以取所有数字

    (Button) plusBtn = (Button) findViewById(R.id.plusBtn);
    plusBtn.setOnClickListener(new OnClickListener(){
    @Override
    public voidonClick(View v){
    number1 = Integer.parseInt(txtScreen.getText().toString());
    });
    

    其中 number1 是全局整数。但我不知道它如何帮助你,以及它是否是一个好方法。您可以找到更好的解决方案,只需记住如何将 TextView 中的 String 解析为 Integer 以进行计算。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-25
      • 1970-01-01
      • 2015-05-03
      • 2014-05-01
      相关资源
      最近更新 更多