Android 具有IntEditTextPreference的NumberFormatException
在我的android应用程序中,我使用了一个名为“IntEditTextPreference”的类。当我希望用户将首选项作为整数引入时,使用该类 但它有一个问题。当用户将字段留空并按“确定”时,将引发NumberFormatException 当字段为空时,如何避免用户按“确定” 谢谢Android 具有IntEditTextPreference的NumberFormatException,android,preference,Android,Preference,在我的android应用程序中,我使用了一个名为“IntEditTextPreference”的类。当我希望用户将首选项作为整数引入时,使用该类 但它有一个问题。当用户将字段留空并按“确定”时,将引发NumberFormatException 当字段为空时,如何避免用户按“确定” 谢谢 public class IntEditTextPreference extends EditTextPreference { public IntEditTextPreference(Context c
public class IntEditTextPreference extends EditTextPreference
{
public IntEditTextPreference(Context context)
{
super(context);
}
public IntEditTextPreference(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public IntEditTextPreference(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
@Override
protected String getPersistedString(String defaultReturnValue)
{
return String.valueOf(getPersistedInt(-1));
}
@Override
protected boolean persistString(String value)
{
return persistInt(Integer.valueOf(value));
}
}通常,如果您使用的是基于浏览器的应用程序,那么在输入有效时,您将使用JavaScript/AJAX显示一个按钮。这已经在客户端处理了。 为了避免出现
NumberFormatException,
只需在Integer.valueOf(value)
语句周围添加一个try
-catch
-块即可
基本上,这取决于您的客户机框架。可能有更好的特定于框架的解决方案。您使用哪一个?您可能仍然应该在其周围有一个try/catch块来捕获
NumberFormatException
。但是有很多方法可以做到这一点。一种方法是,您可以使用按钮setClickable
方法将文本设置为false
,然后使用onTextChangedListener将文本设置为非空且为整数时设置为true。或者,您可以简单地让它可以单击,但在单击按钮时检查是否有空字符串或非整数,并使用警告消息toast/alert/label让用户知道他们的字段不正确,然后再允许按钮执行其他操作。希望这有帮助 persistin方法在哪里?Doh。。。这就解释了安卓标签。Sry,目前深陷基于Web的开发,无法意识到可能会有一些不同。谢谢!我做到了。在EditTextPreference的构造函数中,我创建了一个EditTextWatcher,并与preference的EditText关联getEditText()。addTextChangedListener(watcher)
。然后,在watcher中,我检查字段是否为空,并根据它禁用或启用按钮。