ClassCastexception:无法转换为android.support.v7.preference.Preference

时间:2018-12-16 18:32:02

标签: android android-fragments appcompat-v7-r21

当试图给我的xml文件充气时,我得到了classcastexception。这是我的第一个Android项目,因此我仍在学习中。但是我不知道如何更正我的代码,以便可以为我的类“ SummaryShowingEditTextPreference”充气。运行我的代码时,出现以下错误:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.flow, PID: 13800
    android.view.InflateException: Binary XML file line #12: Error inflating class com.example.flow.displayClasses.AccountScreen.SummaryShowingEditTextPreference
        at android.support.v7.preference.PreferenceInflater.createItem(PreferenceInflater.java:266)
        at android.support.v7.preference.PreferenceInflater.createItemFromTag(PreferenceInflater.java:295)
        at android.support.v7.preference.PreferenceInflater.rInflate(PreferenceInflater.java:362)
        at android.support.v7.preference.PreferenceInflater.rInflate(PreferenceInflater.java:364)
        at android.support.v7.preference.PreferenceInflater.inflate(PreferenceInflater.java:170)
        at android.support.v7.preference.PreferenceInflater.inflate(PreferenceInflater.java:120)
        at android.support.v7.preference.PreferenceManager.inflateFromResource(PreferenceManager.java:138)
        at android.support.v7.preference.PreferenceFragmentCompat.addPreferencesFromResource(PreferenceFragmentCompat.java:429)
        at com.example.flow.displayClasses.AccountScreen.PreferenceFragmentAccount.onCreatePreferences(PreferenceFragmentAccount.java:25)
        at android.support.v7.preference.PreferenceFragmentCompat.onCreate(PreferenceFragmentCompat.java:228)
        at android.support.v4.app.Fragment.performCreate(Fragment.java:2414)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1418)
        at android.support.v4.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1195)
        at android.support.v4.app.FragmentTransition.calculateFragments(FragmentTransition.java:1078)
        at android.support.v4.app.FragmentTransition.startTransitions(FragmentTransition.java:117)
        at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2408)
        at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
        at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.ClassCastException: com.example.flow.displayClasses.AccountScreen.SummaryShowingEditTextPreference cannot be cast to android.support.v7.preference.Preference
        at android.support.v7.preference.PreferenceInflater.createItem(PreferenceInflater.java:259)

这是我的类,它调用preferencesFragmentAccount文件:

public class AccountFragment extends Fragment {
    private FragmentActivity myContext;
    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;
    private View RootView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }


    @Override
    public void onAttach(Activity activity) {
        myContext=(FragmentActivity) activity;
        super.onAttach(activity);
    }

        private static final String TAG = AccountFragment.class.getSimpleName();
        private static final String ARG_SECTION_NUMBER = "section_number";
        public static final int TAB_PRIVATE = 1;
        public static final int TAB_CORP = 2;

        public AccountFragment() {
        }

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

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {

            RootView = inflater.inflate(R.layout.fragment_account, container, false);

            Log.i(TAG, "onCreateView()");

            // Create the adapter that will return a fragment for each of the three
            // primary sections of the activity.
            mSectionsPagerAdapter = new SectionsPagerAdapter(myContext.getSupportFragmentManager());

            // Set up the ViewPager with the sections adapter.
            mViewPager = (ViewPager) RootView.findViewById(R.id.container);
            mViewPager.setAdapter(mSectionsPagerAdapter);

            //BUTTON
            Button openSettingsButton = RootView.findViewById(R.id.open_settings);

            openSettingsButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //Intent i = new Intent(getContext(), PreferenceFragmentAccount.class);
                    //startActivity(i);

                    Fragment preferenceFragmentAccount = new PreferenceFragmentAccount();
                    FragmentTransaction ft =myContext.getSupportFragmentManager().beginTransaction();
                    ft.add(R.id.relativelayout_for_fragment, preferenceFragmentAccount);
                    ft.commit();

                }
            });

            return RootView;
        }

这个类被错误地强制转换,但是我不知道如何在android.support.v7中使用它:

public class SummaryShowingEditTextPreference extends EditTextPreference {

    public SummaryShowingEditTextPreference(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public SummaryShowingEditTextPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SummaryShowingEditTextPreference(Context context) {
        super(context);
    }

    // According to ListPreference implementation
    @Override
    public CharSequence getSummary() {
        String text = getText();
        if (TextUtils.isEmpty(text)) {
            CharSequence hint = getEditText().getHint();
            if (!TextUtils.isEmpty(hint) || super.getSummary().equals("%s")) {
                return hint;
            } else {
                return super.getSummary();
            }
        } else {
            CharSequence summary = super.getSummary();
            if (!TextUtils.isEmpty(summary)) {
                return String.format(summary.toString(), text);
            } else {
                return summary;
            }
        }
    }
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您错误地初始化了EditTextPrefrence。这是您可以正确执行的操作。无需将其扩展为 Fragment ,而是将其扩展为 PrefrenceFragment

    public class AccountFragment extends PrefrenceFragment{

     //Your variable
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    //Prefrence file
            addPreferencesFromResource(R.xml.preference);
        }
//do what you want
}

XML看起来像这样

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory android:title="Main">
        <CheckBoxPreference android:title="Enable Preferences"
            android:key="EnablePreferences" android:summary="Check to enable Other Preferences" />
    </PreferenceCategory>
    <PreferenceCategory android:title="Other Prefernces">
        <ListPreference android:title="List Preference"
            android:key="DayOfWeek" android:dependency="EnablePreferences"
            android:summary="Selec Day of the Week" android:entries="@array/daysOfWeek"
            android:entryValues="@array/daysOfWeekValues" />
        <EditTextPreference android:title="Edit Text Preference"
            android:key="Name" android:dependency="EnablePreferences"
            android:summary="Enter Your Name" android:dialogTitle="Enter Your Name"
            android:defaultValue="Android Partaker"/>
        <RingtonePreference android:title="Ringtone Preference"
            android:key="Ringtone" android:dependency="EnablePreferences"
            android:summary="Select Ringtone" android:ringtoneType="all" />
    </PreferenceCategory>

    <PreferenceCategory android:title="Advance Preference">
        <PreferenceScreen android:title="Advance Preference">

            <EditTextPreference android:title="Enter Text"
                android:key="Text" />
        </PreferenceScreen>
    </PreferenceCategory>
</PreferenceScreen>