我尝试创建必须通过NavigationDrawer打开的PreferenceFragment,但是它不能正常工作。
MainActivity.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
...
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private void setupNavigationDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem item) {
mDrawerLayout.closeDrawers();
setTitle(item.getTitle());
switch (item.getItemId()) {
...
case R.id.nav_one:
setFragment(3);
return true;
case R.id.nav_two:
setFragment(4);
return true;
case R.id.nav_settings:
getFragmentManager().beginTransaction()
.replace(R.id.content_main, new SettingFragment())
.commit();
return true;
}
return true;
}
});
}
public void setFragment(int position){
mFragmentTransaction = getSupportFragmentManager().beginTransaction();
Fragment fragment = null;
switch (position){
...
fragment = new OneFragment();
break;
case 4:
fragment = new TwoFragment();
break;
case 5:
break;
}
mFragmentTransaction.replace(R.id.content_main, fragment);
mFragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
mFragmentTransaction.commit();
}
}
SettingFragment.java
public class SettingFragment extends PreferenceFragment {
public SettingFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
}
}
它看起来像 enter image description here SettingFragment被插入到其余片段的顶部,并且在单击其他片段之后不会被破坏。
这个类似的问题enter link description here
没有帮助我。
有人知道解决方案吗?
解决方案:使用PreferenceFragmentCompat代替PreferenceFragment。