-2
我無法使用我的片段,當選擇導航欄上的項目時它不會顯示,因爲它應該在選擇R.id.nav_gallery時進行選擇。我認爲onNavigationItemSelected(MenuItem項)的某處存在問題,但我無法對其進行本地化。有什麼想法嗎?選定的導航欄上不顯示片段?
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
(...)
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
public static class PlaceholderFragment extends Fragment{
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance() {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, 0);
fragment.setArguments(args);
Log.d("frag", "6");
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
FragmentManager fragmentManager = getFragmentManager();
PlaceholderFragment fragment;
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
fragment = new PlaceholderFragment();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
PlaceholderFragment.newInstance();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
更換片段後,你爲什麼要創建的newInstance? –