Oliver
Oliver

Reputation: 997

Difference between using androidx.preference.PreferenceScreen and PreferenceScreen

My app targets API 28 and has a minimum API 15. As support library, I'm using AndroidX.
I have a preference fragment hosted by an activity, like this:

SettingsFragment.java

package com.example.app;

import android.os.Bundle;

import androidx.preference.PreferenceFragmentCompat;

public class SettingsFragment extends PreferenceFragmentCompat {

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.preferences, rootKey);

    }
}

SettingsActivity.java

package com.example.app;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

public class SettingsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();
    }
}

And here is the XML layout used by SettingsFragment.java

preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <SwitchPreference
        android:defaultValue="false"
        android:key="pref_switch"
        android:title="@string/switch" />
</PreferenceScreen>

As the root of the preference hierarchy, should I use PreferenceScreen or androidx.preference.PreferenceScreen for the layout to actually be backward compatible (using AndroidX)? What is the difference between the two? What is the best practice?

Upvotes: 5

Views: 9844

Answers (1)

karan
karan

Reputation: 8853

From the docs:

AndroidX is the open-source project that the Android team uses to develop, test, package, version and release libraries within Jetpack.

AndroidX is a major improvement to the original Android Support Library. Like the Support Library, AndroidX ships separately from the Android OS and provides backwards-compatibility across Android releases. AndroidX fully replaces the Support Library by providing feature parity and new libraries. In addition AndroidX includes the following features:

  • All packages in AndroidX live in a consistent namespace starting with the string androidx. The Support Library packages have been mapped into corresponding androidx.* packages. For a full mapping of all the old classes and build artifacts to the new ones, see the Package Refactoring page.

So in simple words it is new library that you should use instead of support library as it have latest components and features.

Thus, your PreferenceScreen is same as androidx.preference.PreferenceScreen but bundled with different wrapper.

Upvotes: 2

Related Questions