Search code examples
androiduser-interfaceandroid-preferencespreferencespreferenceactivity

Implement a split preference in Android


I feel like there must be a straight-forward way to achieve this, but I haven't found it so far.

Essentially, in the stock settings app, there are a handful of preferences that are "split" - i.e., tapping on the text of the preference does one thing, while tapping the icon to the right does another.

Screenshot of Display settings, where adaptive brightness checkbox is split

I tried making a custom preference that extends PreferenceGroup, but it seems like PreferenceGroup doesn't really wrap the child views the way a LinearLayout does, for example, but rather just puts all the child views below it. I tried instead extending from LinearLayout but it seems the PreferenceScreen only allows Preferences as children.

My question is more or less what the best way to do this is:

  1. Make a custom preference that does somehow take other preferences as children and display them correctly (this seems like it would be ideal, but I'm not sure how I'd achieve it)
  2. Make a custom preference that, when tapped on, somehow figures out which part was tapped and runs the correct handler (this seems more straightforward, especially if a lot of it is hardcoded into the Kotlin class for the preference, rather than being configured in the XML)
  3. Something else that I haven't thought of.

Like I said, it seems like this shouldn't be too hard, but I haven't found any other recent questions about it on SO. I did find this question but it was asked and answered in 2012, without super clear instructions. There's also this question which asks about something somewhat similar but is nearly 11 years old and the only answer is fairly useless.

Please let me know if there is something I have totally overlooked (maybe I've been using the wrong search terms??) or if you have any suggestions! Thank you!


Solution

  • So, it doesn't appear that this is very possible with the xml format for a settings page, so I decided to implement my settings activity in Jetpack Compose. My solution is by no means the most elegant (and needs more comments, I know), but how to do this the "proper" way is definitely beyond my knowledge.

    EDIT:

    I made some changes to the preferences (most notably, ditching SharedPreferences in favor of Preferences DataStore) and to make it easier, I'm just going to put the link to the GitHub where the files are (and then y'all can see them in a full example):

    Hope this is helpful!