简体   繁体   中英

Android: combine PreferenceFragment with other widgets in single layout

I'm trying to have an Activity that shows just a few (or one) preference item(s) and some more widgets in the remaining space. I'm having a hard time figuring out how to do this.

in /res/xml/preferences_1.xml :

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
    <CheckBoxPreference 
        android:key="test" 
        android:title="test" 
        android:defaultValue="false" />
</PreferenceScreen>

The layout for the activity that I'd like to contain an ui to edit this single preference: /res/layout/test.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <fragment
        android:name="com.test.something.TestActivity$PrefsFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <View ... stuff ... />
</LinearLayout>

And the Activity :

public class TestActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public static class PrefsFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // Load the preferences from XML resource
            this.addPreferencesFromResource(R.xml.preference_login);
        };
    }
}

This should illustrate what I'm trying to achieve: having the <fragment> show the PreferenceFragment and below that still have a (or some) widget(s).

Sadly, this doesn't work as I had hoped. Instead it throws when opening the activity. The relevant part of the stack trace seems to be:

E/AndroidRuntime(12584): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.something/com.test.something.TestActivity}: android.view.InflateException: Binary XML file line #7: Error inflating class fragment

Could someone show me how this is done?

Argh! Later on in the stacktrace there was actually a much more helpful message. The <fragment> was missing an android:id attribute.

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