0

TL;DR:

This line compiles:

int resid = android.R.layout.preference_category;

But this line does not:

int resid = android.R.layout.preference;

The error is "cannot find symbol variable preference". But both resources are clearly available in the Sdk\platforms\android-28\data\res\layout directory!

Why does this happen?

Background

I can navigate (in the IDE) to the preference_category resource, and sure enough, the preference.xml layout is right next to it, along with about a thousand other layouts that, similarly, will not compile.

My build.gradle (excerpt):

compileSdkVersion 28

defaultConfig {
    minSdkVersion 18
    targetSdkVersion 26
}

I recently switched my app over to AndroidX. For the most part, everything went smoothly, except I noticed my preferences had new visual styles. I wouldn't care, except that I had "subclassed" preference.xml by copying the original Android layout, making a trivial change, and then specifying that layout in my prefs.xml, e.g.:

...
<androidx.preference.CheckBoxPreference
    android:key="@string/pref_audio"
    android:title="Audio"
    android:defaultValue="false"
    android:layout="@layout/my_custom_preference"
    />
...

Preferences that I've handled in this way still look like they used to -- the way they looked before I switched to AndroidX. But all the other preferences now look drastically different.

I went back to the API level 28 folder, and checked the contents of Android's original preference.xml, to see if it had changed (since I originally copied/subclassed it). It has not! Yet, the styles of the preferences have changed.

To troubleshoot, I tried to verify that android.R.layout.preference was actually pointing to the resource I was looking at, which led me to the above mentioned compilation error.

Martin Zeitler
  • 1
  • 19
  • 155
  • 216
greeble31
  • 4,894
  • 2
  • 16
  • 30

1 Answers1

1

Just don't use the framework's preferences (incl. resource android.R.layout.preference_category), but androidx.preference. This also features a new one PreferenceManager, which should be used instead. Mixing up android.preference with androidx.preference may lead to unexpected results. Once posted one custom PreferenceCompatActivity, which might be a suitable starting-point.

Martin Zeitler
  • 1
  • 19
  • 155
  • 216
  • This answer set me on the right path. I didn't realize that androidx had its own layout resources which are different from the platform resources. I still don't understand why I can't refer to a resource that is present in the platform sdk, but that is less important now. Thank you. – greeble31 Oct 03 '19 at 22:12
  • @greeble31 `compileSdkVersion` and `targetSdkVersion` should both be 28 or 29... and inflating a `Preference` into a `CheckboxPreference` is questionable, because there is no check-box contained. – Martin Zeitler Oct 04 '19 at 01:15