您好我有一个已经使用导航抽屉的Android应用。 我的 MainActivity扩展了片段活动,我的 SettingFragment扩展了PreferenceFragment
设置片段:
public class SettingsFragment extends PreferenceFragment {
public SettingsFragment() {}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.prefs);
}
}
和我的 MainActivity :
PreferenceFragment preferenceFragment = new SettingsFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(android.R.id.content, preferenceFragment); // I'm getting an error here should be Fragment not PreferenceFragment
ft.commit();
我如何提交或转到SettingsFragment()?
答案 0 :(得分:13)
使用一个简单的片段包装您当前的PreferenceFragment,该片段注意但打开prefenceFragment,如下所示
public class SettingsActivity extends Fragment {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getActivity().getFragmentManager().beginTransaction()
.replace(android.R.id.content, new MyPreferenceFragment())
.commit();
}
private class SettingsFragment extends PreferenceFragment {
public SettingsFragment() {}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.prefs);
}
}
}
答案 1 :(得分:2)
这对我有用。 请记住,此代码适用于api leval 11及更高版本。
在Activity中使用此代码添加Fragment。
android.app.Fragment infoFragment = new InfoFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(android.R.id.content, infoFragment);
ft.commit();
您的PreferenceFragment类将如下所示。
public class InfoFragment extends PreferenceFragment
{
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static android.app.Fragment newInstance(int sectionNumber)
{
InfoFragment fragment = new InfoFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public InfoFragment()
{
}
}
答案 2 :(得分:0)
这个怎么样:
Fragment preferenceFragment = new SettingsFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(android.R.id.content, preferenceFragment);
ft.commit();