How to apply InputFilter to EditTextPreferences?

亡梦爱人 提交于 2019-12-11 05:25:43

问题


I want to apply InputFilter to my EditTextPreferences...

Before I used the PreferenceActivity I had EditTexts with Filters like that:

            et1 = (EditText) findViewById(R.id.editText1);
            et2 = (EditText) findViewById(R.id.ETminsim);
            et3 = (EditText) findViewById(R.id.ETdelay);

            et1.setText(Integer.toString(PlotView.playlist_size), EditText.BufferType.EDITABLE);

            et2.setText(Integer.toString(conversorToInt(PlotView.min_sim)), EditText.BufferType.EDITABLE);
            et3.setText(Integer.toString(MusicService.getSeek()/1000), EditText.BufferType.EDITABLE);

            et1.setFilters(new InputFilter[]{ new InputFilterMinMax(1, 30)});
            et2.setFilters(new InputFilter[]{ new InputFilterMinMax(0, 100)});
            et3.setFilters(new InputFilter[]{ new InputFilterMinMax(0, 300)});

But how can I reference to the EditTexts of the EditTextPreference in order to set these Filters?

My new Code:

public void onCreate(Bundle bundle) {
                 super.onCreate(bundle);

                 getPreferenceManager().setSharedPreferencesName(Singleton.PREFS_NAME);
                 addPreferencesFromResource(R.xml.prefs);

                 //TODO set InputFilter
}

回答1:


Konstantin had it mostly correct. Combine his answer with Sebastian's comment on his answer and you get

EditText editText1 = ((EditTextPreference) findPreference(preference_1_key))
                         .getEditText();
editText1.setFilters(new InputFilter[]{ new InputFilterMinMax(1, 30) });



回答2:


Assuming this is your preference Activity and you can get the items by id:

        EditTextPreference editTextPreference = findByViewId(R.id.editPref1);
        EditText editText = editTextPreference.getEditText();
        editText.setFilters(................);



回答3:


This has more flexibility.

public class Utility {
public static void setEditTextInputFilter(EditText editText, final String blockCharacterSet) {
    InputFilter filter = new InputFilter() {

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

            if (source != null && blockCharacterSet.contains(("" + source))) {
                return "";
            }
            return null;
        }
    };

    editText.setFilters(new InputFilter[]{filter});
}

}

How to use:

exampleEditText is the editText which want to block input "-".

Utility.setEditTextInputFilter(exampleEditText, "-");


来源:https://stackoverflow.com/questions/10581337/how-to-apply-inputfilter-to-edittextpreferences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!