Hide a Preference-item depending on the state (enabled/disabled) of another Preference in PreferenceScreen

182 views Asked by At

I'm creating a settings screen, and I have a few settings items: SwitchPreferenceCompat and my CustomPreference.

I need the СustomPreference to disappear(hide) when the SwitchPreferenceCompat is turned off and appear(show) when the SwitchPreferenceCompat is turned on.

Out of the box, only the "dependency" mechanism is available by specifying the "dependency" attribute for some Preferences, which only disables/enables items, and I need to change visibility.

Is there a way to achieve this?

1

There are 1 answers

0
WannaBe On

create customPreference and override onDependencyChanged().

package com.paul.ttcapp.p9988030.helper.ui;

import android.content.Context;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.preference.EditTextPreference;
import androidx.preference.Preference;

public class PaulEditTextPreference extends EditTextPreference {
    public PaulEditTextPreference(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public PaulEditTextPreference(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public PaulEditTextPreference(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public PaulEditTextPreference(@NonNull Context context) {
        super(context);
    }

    @Override
    public void onDependencyChanged(@NonNull Preference dependency, boolean disableDependent) {
        // If the corresponding dependency is disabled, disable (hide) this setting as well.
        setVisible(!disableDependent);
        super.onDependencyChanged(dependency, disableDependent);
    }
}