2017-03-12 74 views
0
我使用PreferenceFragment

,並試圖調用DialogFragmentPreferenceFragment或PreferenceFragmentCompat

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' 

Whem我改變PreferenceFragment上PreferenceFragmentCompat走了這個錯誤,但出現在片段交易新

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' 

什麼是錯的,如何糾正呢?

回答

0

使用getSupportFragmentManager與支持片段而不是getFragmentManager