如何从Activity转到PreferenceFragment?

时间:2016-03-22 03:31:45

标签: java android android-fragments

我无法从我的主页Activity导航到使用PreferenceFragment的帐户设置页面。

我正在尝试通过导航抽屉实现此功能,单击该项目时,应显示设置页面。我的所有其他页面都是Fragment,但帐户设置页面除外,所有页面都正常工作(设置页面除外)。我认为PreferenceFragmentFragment延伸,所以它肯定会起作用吗?

MainPage.java

@Override
public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    FragmentManager fragmentManager = getSupportFragmentManager();
    if (position == 0) {
        fragmentManager.beginTransaction()
                .replace(R.id.container, PlaceholderFragment.newInstance(1))
                .commit();

    } else if (position == 1) {
        fragmentManager.beginTransaction()
                .replace(R.id.container, Search.newInstance(2))
                .commit();

    }

    else if (position == 2) {
        fragmentManager.beginTransaction()
                .replace(R.id.container, Favourites.newInstance(3))
                .commit();
    }

    else if (position == 3) {
        fragmentManager.beginTransaction()
                .replace(R.id.container, History.newInstance(4))
                .commit();

    }

    else if (position == 4) {
        fragmentManager.beginTransaction()
                .replace(R.id.container, AccountSettings.newInstance(5))
                .commit();

    }

}

AccountSettings.java

public class AccountSettings extends PreferenceFragment {

    Activity mActivity;

    private static final String ARG_SECTION_NUMBER = "section_number";

    public static AccountSettings newInstance(int sectionNumber) {
        AccountSettings fragment = new AccountSettings();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);    //inflating layout
        addPreferencesFromResource(R.xml.settings);
        setHasOptionsMenu(true);
        restoreActionBar();

    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = activity;

    }

    public void restoreActionBar() {
        ActionBar actionBar = ((AppCompatActivity)getActivity()).getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle("Account Settings");
    }

    public AccountSettings() {

    }
}

它会在 MainPage.java

上给我以下错误
'replace(int, android.support.v4.app.Fragment)' in 'android.support.v4.app.FragmentTransaction' cannot be applied to '(int, com.example.laptop.whatsfordinner.AccountSettings)'

我已尝试将其更改为Fragment并且可以正常使用,但我想使用PreferenceFragment,那么我该如何才能使用它?

当然,我只是遗漏了一些非常明显的东西?

1 个答案:

答案 0 :(得分:0)

您需要使用getFragmentManager进行PreferenceFragment。因为他们没有扩展支持v4版本的Fragment类。