PreferenceActivity: save value as integer

前端 未结 5 702
一向
一向 2020-12-12 17:00

Using a simple EditTextPreference in my preferences activity:



        
5条回答
  •  隐瞒了意图╮
    2020-12-12 17:50

    You could extend EditTextPreference:

    public class IntEditTextPreference extends EditTextPreference {
    
        public IntEditTextPreference(Context context) {
            super(context);
        }
    
        public IntEditTextPreference(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public IntEditTextPreference(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }
    
        @Override
        protected String getPersistedString(String defaultReturnValue) {
            return String.valueOf(getPersistedInt(-1));
        }
    
        @Override
        protected boolean persistString(String value) {
            return persistInt(Integer.valueOf(value));
        }
    }
    

    It would be better to overwrite onSetInitialValue() and setText() methods, but then you would have to copy some code from a base class. Above solution is simplier, but it's quite tricky - "string" methods do something with ints. Try to not extend this class further ;-)

    You could use it from XML by:

    
    

提交回复
热议问题