ANDROID – SETTINGS ACTIVITY Template

If you need only one screen with a few settings then read this post. If you need multiple sub-screens of setting then you should use the Settings Activity Template. It divides the settings into fragments and groups. Let’s start.

  • Right-click your app’s package and click New > Activity > Settings Activity. Change the title if you wish, and click the 3 dots … at the right of Hierarchical Parent to specify the parent Activity. Click Finish.
Settings Activity Template, <span>ANDROID – SETTINGS ACTIVITY  Template</span>, KandZ
  • A new resource directory will be created, xml, and 4 resource XML files.
Settings Activity Template, <span>ANDROID – SETTINGS ACTIVITY  Template</span>, KandZ

  • pref_headers.xml – is the layout for the headers, is the settings main screen. The other files are the layouts for each section.
Settings Activity Template, <span>ANDROID – SETTINGS ACTIVITY  Template</span>, KandZ

It has 3 headers/sections, specified with the header element. Each section must have 3 child elements:

  1. android:fragment – specifies the xml will be loaded. first the package, the settings activity, $ that specifies a nested class, and then the nested class
  2. android:icon – specifies the icon
  3. android:title – specifies the title.
Settings Activity Template, <span>ANDROID – SETTINGS ACTIVITY  Template</span>, KandZ
this is the one of the three xml section files

  • In the java directory two class files created, AppCompatPreferenceActivity which is a helper class for the SettingsActivity. In the second class file you will find the nested classes that are used in the pref_headers.xml
Settings Activity Template, <span>ANDROID – SETTINGS ACTIVITY  Template</span>, KandZ
this is one of the three nested classes
  • If you want to create a new section, you must :
  1. Create a new xml resource file that describes the section. It must have a PreferenceScreen parent element and use only preference classes for childs like CheckBoxPreference, ListPreference etc.
Settings Activity Template, <span>ANDROID – SETTINGS ACTIVITY  Template</span>, KandZ

2. Copy one nested class from the SettingsActivity file

3. add a mew entry using the header element in the pref_headers.xml

4. update isValidFragment() method in the SettingsActivity class file.

Settings Activity Template, <span>ANDROID – SETTINGS ACTIVITY  Template</span>, KandZ
  • There have been added new strings in the strings.xml file.
Settings Activity Template, <span>ANDROID – SETTINGS ACTIVITY  Template</span>, KandZ
Settings Activity Template, <span>ANDROID – SETTINGS ACTIVITY  Template</span>, KandZ
Settings Activity Template, <span>ANDROID – SETTINGS ACTIVITY  Template</span>, KandZ

You can modify those or even delete them if you change the 3 layout xml files for the sections.

THE END!!!

97990cookie-checkANDROID – SETTINGS ACTIVITY TemplateANDROID – SETTINGS ACTIVITY Template

Related posts