PreferenceFragment或PreferenceFragmentCompat

时间:2017-03-12 15:51:32

标签: android

我正在使用PreferenceFragment并尝试调用DialogFragment

SettingsActivity.java

public class SettingsActivity extends AppCompatActivity{

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager()
        .beginTransaction()
        .replace(android.R.id.content, new SettingsFragment())
        .commit();
    }

    public static class SettingsFragment extends PreferenceFragment {

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

            Preference switchPreference = (SwitchPreference) findPreference("switch_preference_1");
            switchPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue) {
                    AcceptDialog dialog = new AcceptDialog();
                    dialog.setTargetFragment(SettingsFragment.this, 0);
                    return true;
                }
            });
        }
    }
}

AcceptDialog.java

public class AcceptDialog extends DialogFragment {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new AlertDialog.Builder(getActivity())
                .setTitle("Title")
                .setMessage("Message")
                .create();
    }
}

dialog.setTargetFragment(...);

中的错误
Wrong 1st argument type. Found: 'com.android.cmdev.prefcompattest.SettingsActivity.SettingsFragment', required: 'android.support.v4.app.Fragment'

我在PreferenceFragmentCompat上更改了PreferenceFragment,这个错误消失了,但在片段事务中出现了新的

getFragmentManager()
        .beginTransaction()
        .replace(android.R.id.content, new SettingsFragment())
        .commit();

错误:

Wrong 2nd argument type. Found: 'com.android.cmdev.prefcompattest.SettingsActivity.SettingsFragment', required: 'android.app.Fragment'

有什么问题以及如何纠正?

1 个答案:

答案 0 :(得分:0)

将getSupportFragmentManager与支持片段一起使用,而不是使用getFragmentManager