简体   繁体   English

Android Studio:无需按钮即可添加两个数字

[英]Android Studio: Adding two numbers wihout a button

I'm using Android Studio to develop a program which adds two numbers.我正在使用 Android Studio 开发一个添加两个数字的程序。 First, I used a button to start the calculation but now I don't want to use that button anymore so I'm searching for a possibility to add two numbers in real time.首先,我使用一个按钮开始计算,但现在我不想再使用该按钮,所以我正在寻找一种实时添加两个数字的可能性。 If I change one number, the result should appear instantly.如果我更改一个数字,结果应该会立即出现。 Do you have any suggestions?你有什么建议吗? This is my code für the button variant:这是我的按钮变体代码:

New code:新代码:

 public class MainActivity extends AppCompatActivity {
    EditText firstNumEditText, secondNumEditText;
    TextView resultTextView;

    class MyTextWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String second = secondNumEditText.getText().toString().trim();
            String first = firstNumEditText.getText().toString().trim();
            int num1 = Integer.parseInt(second);
            int num2 = Integer.parseInt(first);
            int result = num1 + num2;
            resultTextView.setText(result + "");
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        firstNumEditText = (EditText) findViewById(R.id.firstNumEditText);
        firstNumEditText.addTextChangedListener(new MyTextWatcher());
        secondNumEditText = (EditText) findViewById(R.id.secondNumEditText);
        secondNumEditText.addTextChangedListener(new MyTextWatcher());
        resultTextView = (TextView) findViewById(R.id.resultTextView);
    }
}

LogCat's output: LogCat 的 output:

 java.lang.NumberFormatException: For input string: ""
        at java.lang.Integer.parseInt(Integer.java:533)
        at java.lang.Integer.parseInt(Integer.java:556)
        at com.example.aufgabe2.MainActivity$MyTextWatcher.afterTextChanged(MainActivity.java:33)
        at android.widget.TextView.sendAfterTextChanged(TextView.java:8202)
        at android.widget.TextView$ChangeWatcher.afterTextChanged(TextView.java:10381)
        at android.text.SpannableStringBuilder.sendAfterTextChanged(SpannableStringBuilder.java:1218)
        at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:579)
        at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:509)
        at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:508)
        at android.text.method.NumberKeyListener.onKeyDown(NumberKeyListener.java:121)
        at android.widget.TextView.doKeyDown(TextView.java:6284)
        at android.widget.TextView.onKeyDown(TextView.java:6074)
        at android.view.KeyEvent.dispatch(KeyEvent.java:2676)
        at android.view.View.dispatchKeyEvent(View.java:9880)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
        at com.android.internal.policy.DecorView.superDispatchKeyEvent(DecorView.java:403)
        at com.android.internal.policy.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1800)
        at androidx.core.view.KeyEventDispatcher.activitySuperDispatchKeyEventPre28(KeyEventDispatcher.java:130)
        at androidx.core.view.KeyEventDispatcher.dispatchKeyEvent(KeyEventDispatcher.java:87)
        at androidx.core.app.ComponentActivity.dispatchKeyEvent(ComponentActivity.java:126)
        at androidx.appcompat.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:535)
        at androidx.appcompat.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:59)
        at androidx.appcompat.app.AppCompatDelegateImpl$AppCompatWindowCallback.dispatchKeyEvent(AppCompatDelegateImpl.java:2533)
        at com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:317)
        at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:4327)
        at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4298)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3849)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3902)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3868)
        at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3995)
        at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3876)
        at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4052)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3849)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3902)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3868)
        at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3876)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3849)
        at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6210)
        at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6184)
        at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6145)
        at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:3647)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

TextWatcher can help you dynamically get value from EditTexts: TextWatcher可以帮助您动态地从 EditTexts 中获取价值:

  • I added an inner class to implement TextWatcher我添加了一个内部 class 来实现 TextWatcher
  • Passed an Object from that inner class to editText.addOnTextChangedListener将 Object 从内部 class 传递到editText.addOnTextChangedListener
  • I used afterTextChanged() to get result from both EditText and perform my operation.我使用afterTextChanged()从 EditText 获取结果并执行我的操作。
public class MainActivity extends AppCompatActivity {

    private EditText firstNumEditText, secondNumEditText;
    private TextView resultTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        firstNumEditText= findViewById(R.id.firstNumEditText);
        firstNumEditText.addTextChangedListener(new MyTextWatcher());
        secondNumEditText=(EditText) findViewById(R.id.secondNumEditText);
        secondNumEditText.addTextChangedListener(new MyTextWatcher());
        resultTextView=(TextView) findViewById(R.id.resultTextView);
        ...
    }

    class MyTextWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) { }
        @Override
        public void afterTextChanged(Editable s) {
            String second = secondNumEditText.getText().toString().trim();
            String first = firstNumEditText.getText().toString().trim();
            if (!second.isEmpty() && !first.isEmpty()) {
                try {
                    int firstNumber = Integer.parseInt(first);
                    int secondNumber = Integer.parseInt(second);
                    //Do calculation
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

You could use TextWatcher on your EditText to listen the text change event and perform action like Add or Minus.您可以在EditText上使用TextWatcher来监听文本更改事件并执行 Add 或 Minus 之类的操作。

You can do it by adding addTextChangedListener to the editText .您可以通过将addTextChangedListener添加到editText来实现。

editText.addTextChangeListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
             // here you can extract the value from edit text and do the addition
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM