Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8026259
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T23:25:56+00:00 2026-06-04T23:25:56+00:00

Is there a way to create a preference in a PreferenceFragment that accepts only

  • 0

Is there a way to create a preference in a PreferenceFragment that accepts only integer values? I could implement an EditTextPreference and register an OnPreferenceChangeListener in which I could reject the change if the user enters a a string that is not a number, but I would prefer something that is meant for holding only numbers and that does not allow users to enter anything else, maybe showing only a dial pad keyboard.. I don’t such a preference exist, since every descendant of Preference is mapped onto a Boolean (CheckBoxPreference), a String (*EditTextPreference) or a String array (MultiSelectListPreference), i.e. there are no preferences mapped onto integers, but maybe some of you can give me an hint or at least tell me if there are better solutions than the one I’ve proposed above.

Solution proposed by Grey:

EditText editText = ((EditTextPreference)    
                             findPreference("intent_property")).getEditText();
editText.setKeyListener(new NumberKeyListener() {
    @Override
    public int getInputType() {
        // The following shows the standard keyboard but switches to the view 
        // with numbers on available on the top line of chars
        return InputType.TYPE_CLASS_NUMBER;
        // Return the following to show a dialpad as the one shown when entering phone
        // numbers.
        // return InputType.TYPE_CLASS_PHONE
    }

    @Override
    protected char[] getAcceptedChars() {
        return new String("1234567890").toCharArray();
    }
});

Shorter solution, which does not allow varying the keyboard to dialpad but requires less code:

EditText editText = ((EditTextPreference) 
                             findPreference("intent_property")).getEditText();
editText.setKeyListener(new DigitsKeyListener());

I don’t like just one thing about this solution: the user can enter 0000 and it is accepted and saved in the shared preference (which is a String) as “0000”.. this requires you to implement a OnSharedPreferenceChangeListener to intercept changes to shared preferences and remove leading zeros in this preference or implement a change listener directly on this preference and return false to refuse numbers with trailing zeros (tell me if there is a better solution to this last problem which does not involve implementing your own Preference). It would be beautiful if we could modify the newValue in OnPreferenceChangeListener..

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T23:25:59+00:00Added an answer on June 4, 2026 at 11:25 pm

    After reading the proposed solutions, I still think a custom preference is the way to go. I did read your remark in bold text, but setting up a basic EditTextIntegerPreference is actually super simple and it will solve the remaining issue you have when the user enters for example “0000”.

    Just a note up front: since you normally want to be able to use preferences in several places in your app, as far as I’m concerned, a proper implementation of an EditTextIntegerPreference would store its value against an Integer. That way you’ll be able to retrieve the int value anywhere, without the need to first parse or cast it.

    However, to keep this answer to the point and compact, I’m actually going to show an extension of a regular EditTextPreference, which means that under the hood, the value will still be stored as a string. If you’re really keen on getting the ‘proper’ implementation to work, I don’t mind writing that up later on. It shouldn’t be too tricky though, so you might want to have a crack at it yourself first. 🙂

    public class EditTextIntegerPreference extends EditTextPreference {
    
        private Integer mInteger;
    
        public EditTextIntegerPreference(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            getEditText().setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
        }
    
        public EditTextIntegerPreference(Context context, AttributeSet attrs) {
            super(context, attrs);
            getEditText().setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
        }
    
        public EditTextIntegerPreference(Context context) {
            super(context);
            getEditText().setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
        }
    
        @Override public void setText(String text) {
            final boolean wasBlocking = shouldDisableDependents();
            mInteger = parseInteger(text);
            persistString(mInteger != null ? mInteger.toString() : null);
            final boolean isBlocking = shouldDisableDependents(); 
            if (isBlocking != wasBlocking) notifyDependencyChange(isBlocking);
        }
    
        @Override public String getText() {
            return mInteger != null ? mInteger.toString() : null;
        }
    
        private static Integer parseInteger(String text) {
            try { return Integer.parseInt(text); }
            catch (NumberFormatException e) { return null; }
        }    
    }
    

    The reason why this solves the “0000” issue, is that we’re simply casting the user typed value to an int before we store it, and plug it back into a string upon retrieval. That means any leading zeroes (except for ‘0’ as a number of course) will automagically disappear.

    The ‘number’ input type will restrict the user to input only enter numbers, so the parseInteger(...) method is mainly present for sanity reasons, although it will catch a NumberFormatException if you try to enter an empty or null string. Again, you can make this more pretty, which I haven’t done for now.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Is there a way to create tags (just like here on stackoverflow when you
Is there a way to create PERMANENT ROOMS in BigBlueButton? If so, any hints?
Is there a way to create private global variables in JavaScript? I have tried
Is there a way to create printable pairs? pair.toString() looks like this: android.util.Pair@fd55fdb8 ,
is there any way to create a new page at runtime? Maybe generate the
Is there a way to create multi-line labels for the y axis in an
Is there any way to create a new NSString from a format string like
Is there any way to create a naming convention for my primary key constraints
Is there a way to create a second Desktop screen in C# - just
Is there any way to create a property like this C# property in Objective-C?

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.