-
Notifications
You must be signed in to change notification settings - Fork 433
Moving to MaterialNavigationDrawer
This little tutorial shows how to move your current project to MaterialNavigationDrawer
.
- class
MaterialNavigationDrawer
is anActivity
, because it extendsActionBarActivity
- All your current content will be a Fragment content
Create two java classes:
- The navigation drawer class
- The first section class
Follow [this](Set up a Navigation Drawer Activity) guide for setting up the navigation drawer.
now move to the first section class and make it extends Fragment
.
It's the time to move your content!
public class MyOldContentActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
Button button = this.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("Button","Button clicked");
}
});
}
}
becomes...
public class FragmentButton extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout);
Button button = view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("Button","Button clicked");
}
});
return view;
}
}
In short: You need you copy and paste all your onCreate method to the fragment onCreateView method.
Then inflate the layout with the LayoutInflater
instead use setContentView()
and call findViewById
from the view inflated.
Now after moving the layout resources, It's time for other things like menu items. Essentially you should copy and paste your old code into the Fragment or the Navigation Drawer activity. For doing that follow this simple rule: The code I'm looking for needs to be global or it is related to a section view?
For example if you move your optionsMenu
methods into the Navigation Drawer activity class, this means that the menu is visible for all section app, but if it is related to a single section you need to move that code to the Fragment class. (and see this question if you don't know how to have optionsMenu in Fragments)
Now that all code has been moved, it's time to connect your drawer content. Go to your Navigation Drawer activity and create a new section that have your Fragment as a target (check the [Setup](Set up a Navigation Drawer Activity) if you don't remember how to do this)
All activities should be declared in the Android Manifest, so open it and add the new Navigation Drawer activity.
<activity android:name=".MyNavigationDrawerActivity" android:theme="@style/NavigationDrawerTheme" />
N.B. remember that the theme must have a MaterialNavigationDrawerTheme
has a parent!