0

I'm having some difficulties getting a PreferenceFragment to load using XML. It keeps throwing a ClassCastException "PreferenceFragmentClass cannot be cast to android.support.v4.app.Fragment". The code is intended to run on API14 and higher.

Here's my code:

import android.os.Bundle;
import android.preference.PreferenceFragment;

public class SettingsFragment extends PreferenceFragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings);

    }   
}

Here's the code where SettingsFragment is being used in:

import android.app.ActionBar;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;

public class FragmentsSetup extends FragmentActivity {

    private ViewPager viewPager;
    private TabsAdapter tabsAdapter;

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

        viewPager = new ViewPager(this);
        viewPager.setId(R.id.pager);
        setContentView(viewPager);

        final ActionBar actionBar = getActionBar();
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setDisplayShowHomeEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        tabsAdapter = new TabsAdapter(this, viewPager);
        tabsAdapter.addTab(actionBar.newTab().setText(getString(R.string.forwarding_tab).toUpperCase()), ForwardingFragment.class, null);
        tabsAdapter.addTab(actionBar.newTab().setText(getString(R.string.settings_tab).toUpperCase()), SettingsFragment.class, null);
    }
}                        

Any tips would be greatly appreciated.

4

2 回答 2

2

SettingsFragment继承自PreferenceFragmentPreferenceFragment来自片段的原生 API Level 11 实现。但是,它是从 Android Support 包的片段 backportFragmentsSetup继承而来的。FragmentActivity

这种组合是行不通的。

如果您打算支持 API 级别 11 之前的设备,则不能使用PreferenceFragment. 另外,我不确定是否PreferenceFragment可以在 a 之外工作PreferenceActivity(可能,但我从未尝试过)。

于 2013-05-11T17:28:37.763 回答
0

如果您正在为 Android 3.0(API 级别 11)及更高版本进行开发,您应该使用 PreferenceFragment 来显示您的 Preference 对象列表。此外,您可以将 PreferenceFragment 添加到任何活动 - 您不需要使用 PreferenceActivity。

请参阅此处的文档: https ://developer.android.com/guide/topics/ui/settings.html ?

于 2017-07-20T13:08:54.990 回答