Else condition is not being called
我有一个if条件来检查edittext是否为空,如果它是空的,则引发警报。 但是当我向edittext输入一些值时,它也会给我提醒
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | package com.example.calculator; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class Calci extends Activity { TextView t1; EditText e1, e2; Button add, sub, mul, div; Context c=this; String b, a; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_calci); e1 = (EditText) findViewById(R.id.EditText01); e2 = (EditText) findViewById(R.id.EditText02); add = (Button) findViewById(R.id.add); sub = (Button) findViewById(R.id.sub); mul = (Button) findViewById(R.id.mul); div = (Button) findViewById(R.id.div); t1 = (TextView) findViewById(R.id.textView1); a = e1.getText().toString(); b = e2.getText().toString(); add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { if (a.equals("") || b.equals("")){ AlertDialog.Builder a1 = new AlertDialog.Builder(c); // Setting Dialog Title a1.setTitle("Alert Dialog"); // Setting Dialog Message a1.setMessage("PLEASE ENTER SOMETHING"); a1.setPositiveButton("yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int button1) { // if this button is clicked, close // current activity dialog.cancel(); } }); // Showing Alert Message AlertDialog alertDialog = a1.create(); a1.show(); } else { Log.d("sadasd","msg"); int result = Integer.parseInt(a) + Integer.parseInt(b); t1.setText(Integer.toString(result)); // InputMethodManager imm = (InputMethodManager)getSystemService( // Context.INPUT_METHOD_SERVICE); // imm.hideSoftInputFromWindow(add.getWindowToken(), 0); } } }); } } |
我有一个if条件,检查edittext是否为空,如果它是空的,则引发警报。但是当我向edittext输入一些值时,它也会给我警报。
试试这个..
获取
1 2 3 4 5 6 7 8 9 10 11 | add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { a = e1.getText().toString(); b = e2.getText().toString(); if (a.equals("") || b.equals("")){ . . . } |
你在
1 2 3 4 5 6 7 | @Override public void onClick(View arg0) { a = e1.getText().toString(); b = e2.getText().toString(); if (a.equals("") || b.equals("")) { |
实际的原因是在OnCreate()方法中,EditText是空白的,因为您只是初始化它。 您需要的是插入一个文本init,然后检查条件。 因此你需要写
只有当
1 2 3 | add.setOnClickListener(new View.OnClickListener() { a = e1.getText().toString(); b = e2.getText().toString(); |
这必须在click listner中,以便在按下按钮之前获取更新值:
1 2 | a = e1.getText().toString(); b = e2.getText().toString(); |