Android PreferenceFragment No view found for id for fragment

六眼飞鱼酱① 提交于 2019-12-22 10:36:32

问题


So I'm making an android application and I started dealing with preferences, when I simply use a PreferenceActivity, everything works perfectly, however, if I use it with a PreferenceFragment, it crashes right after I click the button that calls intents to SettingsActivity with an error:

FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{*app package*/*app package*.SettingsActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f08003d for fragment SettingsFragment{41cc1a98 #0 id=0x7f08003d}

this is SettingsActivity:

public class SettingsActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //addPreferencesFromResource(R.xml.preference);
        // Display the fragment as the main content.
        getFragmentManager().beginTransaction()
                .replace(R.id.pager, new SettingsFragment())
                .commit();
    }


    public static class SettingsFragment extends PreferenceFragment {

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            addPreferencesFromResource(R.xml.preference);

        }
    }
}

R.id.pager is only a simple viewPager layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
android:id="@+id/pager"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

my preference xml:

<?xml version="1.0" encoding="utf-8"?>

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <CheckBoxPreference
        android:key="pref_sync"
        android:title="Sync?"
        android:summary="Do u wanna sync?"
        android:defaultValue="true" />

</PreferenceScreen>

I'm still quite new to android so any help would be awesome!! Thanks!!

EDIT: Problem solved in comments of correct answer


回答1:


You have to call setContentView(R.layout.view_pager_layout) before

getFragmentManager().beginTransaction().replace(R.id.pager, new SettingsFragment()).commit();


来源:https://stackoverflow.com/questions/24711825/android-preferencefragment-no-view-found-for-id-for-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!