简体   繁体   中英

PreferenceFragment with support library

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'
}

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"

支持库首选项片段的 gradle 依赖项是:

implementation 'com.android.support:preference-v14:28.0.0'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM