Search code examples
androidpreference

Preference screen update summary for preference


I implemented a custom preference by extending RingtonePrefernce. I did override getSummary method which dynamically returns the value of pref when pref is updated.

But the problem is on main pref screen the updated value is not reflected when pref is closed. The only time the pref summay is updated in main screen if i scroll down the main pref screen down/up and when the pref goes out of screen and comes back on screen. So basically when its redrawn.

How do i solve this?

Code for main perf screen which lists all prefs

  public class MainActivity extends PreferenceActivity implements
            OnPreferenceClickListener, Preference.OnPreferenceChangeListener {

@SuppressLint("Deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SoundUtils.stopPlaying();

        ringtoneManager = new RingtoneManager(getApplicationContext());
        featureManager =  FeatureManager.getInstance(this);
        beepActionManager= new BeepActionManager();
        addPreferencesFromResource(R.xml.preferences_settings);
       //other code
  }
}

And in preferences_settings my pref is added as

 <PreferenceCategory android:title="@string/sound_settings">
        <com.mindedges.beephourly.utils.CustomRintonePreference
            android:defaultValue="content://settings/system/notification_sound"
            android:key="ringtone_pref"
            android:ringtoneType="all"
            android:title="@string/hr_beep_tone_title"
            android:summary="@string/hr_beep_tone_summary"/>

        <com.mindedges.beephourly.utils.CustomRintonePreference


    </PreferenceCategory>

Solution

  • I checked your code and I created test project, found solution. I think you should notify your custom preference that you changed it. 'RingtonePreference' has callback method called 'onSaveRingtone' and you need to call 'notifyChnaged' function at overriding of 'onSaveRingtone'. Here is the code I tested.

    public class CustomPreference extends RingtonePreference {
        public CustomPreference(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        public CustomPreference(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public CustomPreference(Context context) {
            super(context);
        }
    
        @Override
        protected void onSaveRingtone(Uri ringtoneUri) {
            super.onSaveRingtone(ringtoneUri);
    
            notifyChanged();
        }
    
        @Override
        public CharSequence getSummary() {
            return "Date " + System.currentTimeMillis();
        }
    }