How create a settings menu with checkbox Android

David_D picture David_D · Jul 4, 2013 · Viewed 7.5k times · Source

I want to create a preference screen in which there are three checkboxes; the first one is clickable and the other two are not until the first is checked.

How can I do this? I've seen this tutorial, but there is only one checkbox. Can anyone help me?

Answer

Dulanga picture Dulanga · Jul 4, 2013
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
     <PreferenceCategory
           android:summary="@string/summary_category"
           android:title="@string/title_category">
           <CheckBoxPreference
                 android:key="main"
                 android:defaultValue="true"
                 android:summary="@string/summary_main"
                 android:title="@string/title_main" 
          />
          <CheckBoxPreference
                android:key="firstDependent"
                android:summary="@string/summary_firstDependent"
                android:title="@string/title_firstDependent"
                android:dependancy="main"
          />
          <CheckBoxPreference
                android:key="secondDependent"
                android:summary="@string/summary_secondDependent"
                android:title="@string/title_secondDependent"
                android:dependancy="main"
          />
    </PreferenceCategory>
<!--Any other categories include here-->
</PreferenceScreen>

You can do this simply by setting android:dependancy to the key of the check box in which the respective check boxes must depend on.

Now create a folder named xml in res folder and put your preferences xml file inside that. Then do the following.

public class SettingsActivity extends PreferenceActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);


    }


}    

You can also do this with fragments which is more recommended. But the above method is much more easy. If you want to do that with fragments, check this which contains everything you need to know about creating a Settings Activity.

Hope this helps.