我有一个if条件,用于检查edittext是否为空,如果为空则会引发警报。但是当我在edittext中输入一些值时,它也会给我提醒
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输入一些值时,它也会给我提醒。
答案 0 :(得分:1)
你在onCreate()
方法中做错了。您应该使用下面的onClick()
方法
@Override
public void onClick(View arg0)
{
a = e1.getText().toString();
b = e2.getText().toString();
if (a.equals("") || b.equals(""))
{
实际的原因是在OnCreate()方法中,EditText是空白的,因为您刚刚初始化它。您需要的是插入一个文本init,然后检查条件。因此你需要写a = e1.getText().toString();
& onClicck()方法中的b = e2.getText().toString();
语句
答案 1 :(得分:1)
试试这个..
获取EditText
ClickListener
文字
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
a = e1.getText().toString();
b = e2.getText().toString();
if (a.equals("") || b.equals("")){
.
.
.
}
答案 2 :(得分:0)
这必须在点击侦听器内部,以便在按下按钮之前获取更新值:
a = e1.getText().toString();
b = e2.getText().toString();
答案 3 :(得分:0)
仅当if (a.equals("") || b.equals(""))
和a
内部都有值时,您的条件b
才会 。因此,只需要填写editTexts
,你也应该在onClick监听器的顶部检查它,因为那时你只是在你的活动开始时才这样做。所以你在a and b
变量中有旧值。
add.setOnClickListener(new View.OnClickListener() {
a = e1.getText().toString();
b = e2.getText().toString();