Using PreferenceScreen with applicationIdSuffix

前端 未结 3 626
情歌与酒
情歌与酒 2021-01-13 06:05

I\'m having some problems making PreferenceScreen and applicationIdSuffix work together.

Supposing my app package/applicationId

相关标签:
3条回答
  • 2021-01-13 06:15

    There is currently no direct way to include the effective applicationId into other XML files than the AndroidManifest (where it is available as ${applicationId}), so you need to create a string property for it.

    Because the gradle applicationId value changes based on the flavor, you can not use it directly to define the string property. Instead, you need to create an afterEvaluate rule in build.gradle to generate it for all variants:

    afterEvaluate {
        android.applicationVariants.all { variant ->
            variant.resValue 'string', 'application_id', variant.applicationId
        }
    }
    

    This will create a @string/application_id (or R.string.application_id) that you can use wherever needed, e.g. in your layout / preferences XML (the class name doesn't need to be changed because it is based on the java package that's the same for all flavors):

    <PreferenceScreen
        android:key="key_about" android:summary="something" android:title="About">
        <intent
            android:targetClass="com.myapp.activities.AboutActivity"
            android:targetPackage="@string/application_id" />
    </PreferenceScreen>
    

    This solution is based on https://gist.github.com/Takhion/74b67cb518e90faf2708 which also provides a provider property.

    0 讨论(0)
  • 2021-01-13 06:32

    Your confusion comes from the fact that applicationIdSuffix only changes the package name of the application (its unique id), but does not change the java package name of your classes inside the application, including your Activity.

    This means that you should declare in your preferences:

    android:targetClass="com.myapp.activities.AboutActivity"
    android:targetPackage="@string/packagename"
    

    Where targetClass is always the same, while targetPackage depends on your build type and can be com.myapp or com.myapp.dev.

    0 讨论(0)
  • 2021-01-13 06:33

    What I do in my app is attach an onPreferenceClickListener to the preference in its host activity, and build the intent inside that listener's onPreferenceClick method. By generating the intent from code, you directly reference the target class and the question of packages never comes up.

    0 讨论(0)
提交回复
热议问题