pgsandstrom pgsandstrom - 1 month ago 9
Android Question

Make Preference look disabled, but still register clicks

So during certain states in my app, I want to disable certain CheckBoxPreferences in my setting-menu. However, if the user clicks them, I want an explanatory toast to be shown. If i just do setEnable(false); on the CheckBoxPreference, I do get the right look and feel. But I cant get a toast to be shown on click. On the other hand, I have failed in manually making a CheckBoxPreference look like it is disabled.

Answer

Instead of disabling the preference, you can as well disable the views of the preference only.

public class DisabledAppearanceCheckboxPreference extends CheckBoxPreference {

        protected boolean mEnabledAppearance = false;

        public DisabledAppearanceCheckboxPreference(Context context,
                AttributeSet attrs) {
            super(context, attrs);

        }
    @Override
    protected void onBindView(View view) {
        super.onBindView(view);
        boolean viewEnabled = isEnabled()&&mEnabledAppearance;
        enableView(view, viewEnabled);
    }

    protected void enableView( View view, boolean enabled){
        view.setEnabled(enabled);
        if ( view instanceof ViewGroup){
            ViewGroup grp = (ViewGroup)view;
            for ( int index = 0; index < grp.getChildCount(); index++)
                enableView(grp.getChildAt(index), enabled);
        }
    }
    public void setEnabledAppearance( boolean enabled){
        mEnabledAppearance = enabled; 
        notifyChanged();
    }
    @Override
    protected void onClick() {
        if ( mEnabledAppearance)
            super.onClick();
        else{
            // show your toast here
        }
    }

}
Comments