Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set only numeric value for EditTextPreference in android?

Tags:

android

how to set only numeric value for EditTextPreference in android. I want a user to enter a port number not sure how can I put the limitation there

I am using this code, user can enter any string. Want to limit the user to atleast numbers only

   <EditTextPreference 
    android:defaultValue="4444" 
    android:key="port" 
    android:title="Port" 
    android:dependency="service_on"        
    />    
like image 758
Ahmed Avatar asked Nov 16 '12 22:11

Ahmed


3 Answers

EditTextPreference widgets should take the same attributes as a regular EditText, so use:

android:inputType="number"

Or more specifically use:

android:inputType="numberDecimal"
android:digits="0123456789"

since you want to limit the input to a port number only.

like image 138
Sam Avatar answered Oct 23 '22 16:10

Sam


I use an androidX library because this library has a possibility to customize an input type of EditTextPreference dialog. AndroidX is a major improvement to the original Android Support Library so is suggested that everybody use this library. You can read more about AndroidX here.

Here is my code where I use EditTextPreference inside of onCreatePreference method:

 @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.preference, rootKey);



androidx.preference.EditTextPreference editTextPreference = getPreferenceManager().findPreference("use_key_from_editTextPreference_in_xml_file");
editTextPreference.setOnBindEditTextListener(new androidx.preference.EditTextPreference.OnBindEditTextListener() {
            @Override
            public void onBindEditText(@NonNull EditText editText) {
                editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);

            }
        });

       }

After you use this code and click on editTextPreference, the dialog will pop up and your keyboard input type will be only numeric.

like image 40
Dezo Avatar answered Oct 23 '22 14:10

Dezo


Using androidx.preference library, since androidx.preference:preference:1.1.0-alpha02 which is realeased on 2018.12.17, the library adds EditTextPreference.OnBindEditTextListener interface, which allows you to customize the EditText displayed in the corresponding dialog after the dialog has been bound.

So in this case, all you have to do is to add the Kotlin code below.

val editTextPreference = preferenceManager.findPreference<EditTextPreference>("YOUR_PREFERENCE_KEY")
editTextPreference.setOnBindEditTextListener { editText ->
                editText.inputType = InputType.TYPE_CLASS_NUMBER
}
like image 18
Brainor Avatar answered Oct 23 '22 15:10

Brainor