9

我已经阅读了关于这个问题的许多答案,但我的问题是问我将代码放在哪里。我正在寻找验证一个数字是否大于 100 EditTextPreference。这是我用来填充首选项的代码:

public class SettingsFrag extends PreferenceFragment{
          
  //Override onCreate so that the code will run when the activity is started.
  @Override
  public void onCreate(Bundle savedInstanceState){        
          //Call to the super class.
          super.onCreate(savedInstanceState);
          
          //add the preferences from the XML file.
          addPreferencesFromResource(R.xml.preferences);
  }

}

是在这里我添加验证还是我必须创建另一个类?

首选项.xml:

<EditTextPreference             
    android:key="geofence_range"             
    android:title="Geofence Size"             
    android:defaultValue="500"     
    android:inputType="number"
    android:summary="Geofence Size Around User Location"             
    android:dialogTitle="Enter Size (meters):" /> 
4

4 回答 4

15

添加setOnPreferenceChangeListenerfor EditTextPreferenceafteraddPreferencesFromResource以验证用户的数据输入:

EditTextPreference edit_Pref = (EditTextPreference) 
                    getPreferenceScreen().findPreference("geofence_range");
   edit_Pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

     @Override
      public boolean onPreferenceChange(Preference preference, Object newValue) {
          // put validation here..
            if(<validation pass>){
              return true;
            }else{
              return false;
             }
       }
    });
于 2014-02-18T14:44:53.323 回答
12

注意:此答案基于已弃用 android.preference.EditTextPreference的.


嗯。另一件在 Android 中本应如此简单但并非如此的事情。其他答案只是默默地阻止将结果写回首选项,这似乎有点粗制滥造。(展示吐司不那么粗制滥造,但仍然是粗制滥造)。

您需要自定义首选项来执行此操作。定制onValidate以满足您的需求。

package com.two_play.extensions;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;

public class ValidatingEditTextPreference extends EditTextPreference {
    public ValidatingEditTextPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public ValidatingEditTextPreference(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public ValidatingEditTextPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ValidatingEditTextPreference(Context context) {
        super(context);
    }

    @Override
    protected void showDialog(Bundle state) {
        super.showDialog(state);
        AlertDialog dlg = (AlertDialog)getDialog();
        View positiveButton = dlg.getButton(DialogInterface.BUTTON_POSITIVE);
        getEditText().setError(null);
        positiveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onPositiveButtonClicked(v);
            }
        });
    }

    private void onPositiveButtonClicked(View v) {
        String errorMessage = onValidate(getEditText().getText().toString());
        if (errorMessage == null)
        {
            getEditText().setError(null);
            onClick(getDialog(),DialogInterface.BUTTON_POSITIVE);
            getDialog().dismiss();
        } else {
            getEditText().setError(errorMessage);
            return; // return WITHOUT dismissing the dialog.
        }
    }

    /***
     * Called to validate contents of the edit text.
     *
     * Return null to indicate success, or return a validation error message to display on the edit text.
     *
     * @param text The text to validate.
     * @return An error message, or null if the value passes validation.
     */
    public String onValidate(String text)
    {
        try {
            Double.parseDouble(text);
            return null;
        } catch (Exception e)
        {
            return getContext().getString(R.string.error_invalid_number);
        }
    }
}
于 2015-07-10T16:11:28.203 回答
2

对我来说,禁用“确定”按钮而不是让用户按下它,然后放弃他们的输入并显示错误似乎更优雅。getDialog似乎消失了androidx.preference,但这似乎对我有用:

final EditTextPreference p = new EditTextPreference(context);
p.setOnBindEditTextListener(new EditTextPreference.OnBindEditTextListener() {
    @Override
    public void onBindEditText(@NonNull final EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                String validationError;
                try {
                    // ... insert your validation logic here, throw on failure ...
                    validationError = null; // All OK!
                } catch (Exception e) {
                    validationError = e.getMessage();
                }
                editText.setError(validationError);
                editText.getRootView().findViewById(android.R.id.button1)
                        .setEnabled(validationError == null);
            }
        });
    }
});
于 2019-12-12T03:00:50.377 回答
1

androidx.preference.*这是我基于Vladimir Panteleev 的回答的Kotlin 实现:

class CustomPreference : EditTextPreference {


    // ...

    private fun applyValidation() = setOnBindEditTextListener { editText ->
        editText.doAfterTextChanged { editable ->
            requireNotNull(editable)
            // TODO Add validation magic here.
            editText.error = if (criteria.isValid()) {
                null // Everything is fine.
            } else {
                if (criteria.getErrorMessage() == null) "Unknown validation error"
                else resources.getString(criteria.getErrorMessage())
            }
        }
    }

}

方便的doAfterTextChanged扩展是androidx.core:core-ktx的一部分。

于 2020-09-12T19:48:16.033 回答