简体   繁体   English

Android EditText首选项验证

[英]Android EditText preference validation

I am using Edittextpreference as one of the preference in settings section. 我使用Edittextpreference作为设置部分中的首选项之一。 I want to validate this edittextpreference when the user enters data to it and clicks ok; 我想在用户向其输入数据并单击确定时验证此edittextpreference; before saving it in sharedpreference. 在将其保存在共享首选项之前。

I am trying to do something like this but this saves the preference first I suppose. 我试图做这样的事情,但这首先保存了我的偏好。

editTextPreference
            .setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference preference,
                        Object newValue) {
                    if (((newValue.toString().length() == 15) {
                          // save preference only if length is equal to 15
                     }
              })
               });

can someone guide me how to validate edittextpreference before it is saved in sharedpreference so that I can decide if I want to save it or not. 有人可以指导我如何验证edittextpreference之前保存在sharedpreference中,以便我可以决定是否要保存它。

According to doc here 根据这里的文件

Called when a Preference has been changed by the user. 当用户更改了首选项时调用。 This is called before the state of the Preference is about to be updated and before the state is persisted. 这将在Preference的状态即将更新之前和状态持久之前调用。

And it returns True to update the state of the Preference with the new value. 它返回True以使用新值更新Preference的状态。

So you can do the following 所以你可以做到以下几点

      editTextPreference
            .setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference preference,
                        Object newValue) {
                    if (((newValue.toString().length() == 15) {
                          //
                          return true;
                     }
                     else{
                          // invalid you can show invalid message
                          return false;
                     }
              })
       });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM