I'm developing an app where I've been using the support library fragments throughout and I stumbled upon this problem where I can't seem to add a PreferencesFragment
(for the settings) using this library?
I've found some suggestions to use v7 PreferenceFragmentCompat
, however looks like for some reason I can't add the v7
support library to my build path, therefore I can't locate the PreferenceFragmentCompat
...
I've tried rewriting the code to use regular fragments instead of the ones in support library, but I had some issues with that too
In case you're wondering, I'm developing with support library because, while reading The Big Nerd Ranch book on android programming, somewhere early on they advise always using support library for fragments.
Any suggestions on the workarounds, or should I just try to switch to non-support version?
Here are the dependencies from my build.gradle:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
}
In Android apps, there are often settings pages that contain different options the user can tweak. The PreferenceFragment and PreferenceFragmentCompat contains a hierarchy of preference objects displayed on screen in a list. These preferences will automatically save to SharedPreferences as the user interacts with them.
The Preference library allows you to build interactive settings screens, without needing to handle interacting with device storage or managing the user interface.
The appcompat v7 library actually uses the v4 support library, so you need to explicitly import the v7 support library components that you need.
In your case, you just need to add compile 'com.android.support:preference-v7:23.1.1'
to your build.gradle:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'com.android.support:preference-v7:23.1.1'
}
Then this will work:
import android.os.Bundle;
import android.support.v7.preference.PreferenceFragmentCompat;
import android.view.View;
public class MyPreferenceFragment extends PreferenceFragmentCompat {
public MyPreferenceFragment() {
// Required empty public constructor
}
@Override
public void onCreatePreferences(Bundle bundle, String s) {
addPreferencesFromResource(R.xml.fragment_settings_pref);
}
}
If you are working with androidx use;
implementation "androidx.legacy:legacy-preference-v14:1.0.0"
implementation "androidx.preference:preference:1.1.1"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With