开发者

Android - How to add a"0" when "button" is clicked if TextBox is empty ""

i want to set a "0" in each "empyt" TextBoxes if the user clicks one button, to avoid an error in the app, any help? i dont know what to do

package com.doko.most;
 import android.app.Activity;
 import android.os.Bundle;
 import android.widget.EditText;
 import android.widget.TextView;
 import android.widget.Button;
 import android.view.View;
public class doko extends Activity {
private EditText bx1;
private EditText bx2;
private TextView txt3;
private Button btncalcular;
private Button btnreset;
private double variable1 = 0;
private double variable2 = 0;
private double variable3 = 0;
    /** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    initControls();
}
private void initControls()
{
bx1 = (EditText)开发者_运维百科findViewById(R.id.bx1);
bx2 = (EditText)findViewById(R.id.bx2);
txt3 = (TextView)findViewById(R.id.txt3);
btncalcular = (Button)findViewById(R.id.btncalcular);
btnreset = (Button)findViewById(R.id.btnreset);
btncalcular.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ calcular(); }});
btnreset.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ reset(); }});
 }

    private void calcular()
 {
variable1 = Double.parseDouble(bx1.getText().toString());
variable2 = Double.parseDouble(bx2.getText().toString());
variable3 = Math.sqrt(1*2/3600);
txt3.setText(Double.toString(variable3));
    }
  private void reset(){
bx1.setText("");

bx2.setText("");

}
   }


try something like this, quick and dirty:

private void calcular() {
    try {
        variable1 = Double.parseDouble(bx1.getText().toString());
    }
    catch(NumberFormatException e) {
        bx1.setText("0");
    }
    try {
        variable2 = Double.parseDouble(bx2.getText().toString());
    }
    catch(NumberFormatException e) {
        bx2.setText("0");
    }
    variable3 = Math.sqrt(1*2/3600);
    txt3.setText(Double.toString(3));
}


set up Hint property at your EditText Ex.

and check it when you getText()

use str.isEmpty() and str.length to check user's inpupt

another way : set up inputType for the EditText to number and setup Input filter ex.

InputFilter[] FilterArray = new InputFilter[1];

FilterArray[0] = new InputFilter.LengthFilter(4);

input.setFilters(FilterArray);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜