问题
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