为Edittext设置defaultValue

时间:2015-11-16 15:33:50

标签: java android

目前,我正在构建一个最大可编辑骰子的骰子应用。 嗯,它的工作原理。但是如果删除edittext中的所有内容,那么Int i的值就像" null"和应用程序崩溃。

为了解决这个问题,我尝试了很多不同的东西,例如异常或大量的" if" -code。

所以我的主要问题不是defaultValue,而是因为"非输入"引起的崩溃。

感谢您的帮助!

2 个答案:

答案 0 :(得分:4)

如果 EditText为空,则可以在其上设置错误。因此,用户可以直观地看出错误。

EditText txtUserName = (EditText) findViewById(R.id.txtUsername);
String strUserName = txtUserName.getText().toString();

 if(TextUtils.isEmpty(strUserName)) {
    txtUserName.setError("Your message");
    return;
 }

它会显示like this.

答案 1 :(得分:0)

如果编辑文本为空,请尝试为字符串变量设置默认值

EditText editText=(EditText) findViewById(R.id.edit_text);
String variable;

if(editText.getText().toString().equals("")){
     variable="Empty";
 }else{
     variable=editText.getText().toString();
     /*Do the rest of the logic */
 }