Search code examples
androidandroid-layoutlayoutpreferenceactivity

Mimic preference screen and displaying key-value attributes


How would I mimic the design of a preference screen or the "edit Contact" screen of android, without doing too much work? I have to display ~12 attributes for an object and can't get my head around how to display them in a good way.

  • not for every attribute an obvious icon exists -> we want labels?
  • displaying textviews underneath other textviews that have an icon looks horrible, except if you want to manually add margins. (indenting)
  • PreferenceFragment has a kind of "Title" that can be used as Label and a Value, which would be even more perfect, as I have some interactive elements (item picker).
  • But using preferencefragment without SharedPreferences and instead to display arbitrary objects is obviously a (bad?) hack.

I've searched a lot and didn't come to a conclusion. Is there an obvious way I missed ?


Solution

  • You can actually create Settings Activity (with full functionality) without much effort.

    Go to File > New > Activity > Settings Activity.

    It will create the entire functionality - you only need to specify Switches, Lists in

    res > xml > prefs_.xml

    The values that you set via screen will be saved in SharedPreferences under the specified key.

    To intercept the values that are configured via UI to the SharedPreferences you can add this to the SettingsActivity:

     class SettingsFragment : PreferenceFragmentCompat() {
        override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
            setPreferencesFromResource(R.xml.pref_general, rootKey)
    
            findPreference<ListPreference>("system_theme")?.setOnPreferenceClickListener { 
                val value = (it as? ListPreference)?.value
                //send value to server
                return@setOnPreferenceClickListener true
            }
         }
      }