ListPreference's summary text is not updated automatically whenever there is change in selection

前端 未结 3 1942
盖世英雄少女心
盖世英雄少女心 2021-02-05 12:33

Although it is being documented, by using \"%s\", I can display selected value as summary, it doesn\'t work as expected.

http://developer.android.com/refere

3条回答
  •  佛祖请我去吃肉
    2021-02-05 13:08

    This is a bug that existed on platforms prior to KITKAT (i.e. android-4.4_r0.7), and it is fixed by commit 94c02a1

    The solution from @ilomambo works, but may not be the best one. I read through the source of ListPreference and came up with this solution:

    File: ListPreferenceCompat.java

    package com.example.yourapplication;
    
    import android.content.Context;
    import android.os.Build;
    import android.preference.ListPreference;
    import android.text.TextUtils;
    import android.util.AttributeSet;
    
    public class ListPreferenceCompat extends ListPreference {
    
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        public ListPreferenceCompat(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
        }
    
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        public ListPreferenceCompat(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        public ListPreferenceCompat(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public ListPreferenceCompat(Context context) {
            super(context);
        }
    
        // NOTE:
        // The framework forgot to call notifyChanged() in setValue() on previous versions of android.
        // This bug has been fixed in android-4.4_r0.7.
        // Commit: platform/frameworks/base/+/94c02a1a1a6d7e6900e5a459e9cc699b9510e5a2
        // Time: Tue Jul 23 14:43:37 2013 -0700
        //
        // However on previous versions, we have to work around it by ourselves.
        @Override
        public void setValue(String value) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                super.setValue(value);
            } else {
                String oldValue = getValue();
                super.setValue(value);
                if (!TextUtils.equals(value, oldValue)) {
                    notifyChanged();
                }
            }
        }
    }
    

    When you need to use ListPreference in xml, simply replace the tag to com.example.yourapplication.ListPreferenceCompat.

    This works neatly on my Samsung S4 device running Android 4.3, and inside one of my production app.

提交回复
热议问题