I want to hide CheckBoxPreference items dynamically on Android

Asked 2 years ago, Updated 2 years ago, 56 views

I would like to hide the Android Preference item dynamically.

<PreferenceScreen>
・・・
        <CheckBoxPreference
            android:key="test_key"
            android:defaultValue="true"
            android: title="@string/test_title"/>
・・・
</PreferenceScreen>


the above items I want to hide it on the code.

CheckBoxPreference test=getCheckBoxPrefInstance("test_key");
if(test!=null){
    test.setSelectable(false);(1)
//    test.setEnabled(false);(2)
}

In the case of (1), it looks like it is active, but it cannot be tapped
(2)In the case of , the indication appears as inactive.

https://developer.android.com/guide/topics/ui/settings/customize-your-settings?hl=ja

EditTextPreference signaturePreference=findPreference("signature");
if(signaturePreference!=null){
    signaturePreference.setVisible(true);
}

As for the EditTextPreference mentioned above, if you look at the above, it would be better to use setVisible.

 if(test!=null){
//    test.setSelectable(false);(1)
//    test.setEnabled(false);(2)
    test.setVisible(false);(3)
}

(3) If setVisible is not found in CheckBoxPreference, you will get in trouble.
Is there a way to hide check box items?

android

2022-09-30 11:46

1 Answers

The official reference CheckBoxPreference specifies setVisible(boolean visible).

If setVisible is not found in CheckBoxPreference, they will get in trouble.

This is not that CheckBoxPreference cannot use the setVisible method, but the cause is completely different. You should think that you can't use what you should be using.

Perhaps import is not done properly.

buile.gradle(:app)

implementation' androidx.preference:preference:1.2.0'//Java

Or

implementation'androidx.preference:preference-ktx: 1.2.0'//Kotlin Java combined

And import statement

import androidx.preference.CheckBoxPreference;

Make sure that android X is selected properly.

Fragment:

public class MySettingsFragment extensions PreferenceFragmentCompat{
    @ Override
    public void onCreatePreferences(@NullableBundle savedInstanceState, @NullableStringrootKey){
        setPreferencesFromResource(R.xml.preferences, rootKey);
        CheckBoxPreference check=findPreference("check");
        check.setVisible(false);
    }
}

preferences.xml

<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto">
    <CheckBoxPreference app:key="check"/>
</PreferenceScreen>

setVisible is done without any problems.


2022-09-30 11:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.