Reputation: 15
I'm trying to make an android app with a sliding navigation drawer.
I have the navigation drawer working.
What I am having trouble with is switching activities when an item from the navigation drawer is selected. I read that I should use fragments over activities. However, I'm not quite clear on how that would work, since I've never worked with fragments before.
Currently when you select an item from the navigation drawer it does not change the layout but simply changes what is on the screen (in this case, changes the number on the screen). I would like it to go to a different layout when that happens.
Here is my code so far:
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView;
rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
Upvotes: 0
Views: 2245
Reputation: 2231
Try using this way to use an activity to your navigation Drawer
private void selectItem1(final int position) {
switch (position) {
case 1:
Intent a = new Intent(this, MainActivity.class);
startActivity(a);
break;
case 2:
Intent b = new Intent(this, Profesori.class);
startActivity(b);
break;
default:
but the best way is to use Fragment in navigationDrawer inorder to do so
Include your Layout inside a FrameLayout
Extend your Activity as
YourActivity extends Fragment
Do other minor neccessary changes such as using OnCreateView
inorder to use Fragment in Your NavigationDrawer in MainActivity
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
switch (id) {
case R.id.item1:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment1, new YourFragment1()).commit();
break;
case R.id.item2:
getFragmentManager().beginTransaction().replace(R.id.fragment1, new YourFragment2()).commit();
break;
}
}
Upvotes: 1