NumberFormatException异常与IntEditText preference [英] NumberFormatException with IntEditTextPreference

查看:164
本文介绍了NumberFormatException异常与IntEditText preference的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Andr​​oid应用程序中,我使用了一个名为IntEditText preference级。当我想用户引入preference为整数,则使用此类。

In my android application, I'm using a class called 'IntEditTextPreference'. This class is used when I want a user to introduce a preference as an integer.

但它有一个问题。当用户离开该字段为空和preSS确定,在抛出NumberFormatException。

But it has a problem. When the user leaves the field empty and press "ok", an NumberFormatException is thrown.

我应该怎么做,以避免用户preSSOK时,该字段为空?

What could I do to avoid the user to press "ok" when the field is empty?

谢谢!

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));
   }

}

推荐答案

您也许应该还是有try / catch块周围搭上 NumberFormatException异常。但也有许多方法可以做到这一点。一种方法是你可以用按钮 setClickable 方法,然后真当文本不为空,是整数使用 onTextChangedListener 。或者,你可以简单地让它可以点击,但检查空字符串和非整数单击按钮时,用一个警告消息敬酒/警报/标签,让用户知道他们有不正确的字段使按钮可以做任何事情之前。希望这有助于!

You should probably still have a try/catch block around it to catch NumberFormatException. But there are many ways to do this. One way is you can use the buttons setClickable method to false and then true when the text is not null and is integer using onTextChangedListener. Or you could simply let it be clickable but check for empty string or non-integer when the button is clicked and use a warning message toast/alert/label to let the user know they have incorrect field before allowing the button to do anything else. Hope this helps!

这篇关于NumberFormatException异常与IntEditText preference的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆