I have implemented in one Android application a Drawer Navigation with Action bar. Now, I want insert Toolbar instead of Action bar, because it is deprecated. But I'm not able to do this.
public class AndroidNavDrawerActivity extends AppCompatActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment fragment;
//FragmentManager fragmentManager = getSupportFragmentManager(); // For AppCompat use getSupportFragmentManager
switch(position) {
default:
case 0:
fragment = new SocialHistoryActivity();
break;
case 1:
fragment = new EncounterActivity();
break;
}
if (fragment != null) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.social_history);
break;
case 2:
mTitle = getString(R.string.encounter);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "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 = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((AndroidNavDrawerActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
This is NavigationDrawerFragment.java
public class NavigationDrawerFragment extends Fragment {
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private NavigationDrawerCallbacks mCallbacks;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
}
// Select the default item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// the fragment has menu items to contribute
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.social_history),
getString(R.string.encounter)
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
private ActionBar getActionBar() {
return ((AppCompatActivity) getActivity()).getSupportActionBar();
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(),
mDrawerLayout,
null,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu();
}
};
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.setDrawerIndicatorEnabled(true);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static interface NavigationDrawerCallbacks {
void onNavigationDrawerItemSelected(int position);
}
}
fragment_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".activity.AndroidNavDrawerActivity$PlaceholderFragment">
<TextView
android:id="#+id/section_label"
android:layout_width="240dp"
android:layout_height="wrap_content" />
</RelativeLayout>
1) Add foll. dependencies to your build.gradle(app level) -
compile 'com.android.support:appcompat-v7:23.x.x'
compile 'com.android.support:design:23.x.x'
2) In your XML file Add -
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:title="Hello"
app:titleTextColor="#FF0000"
android:background="?attr/colorPrimary" />
</android.support.design.widget.AppBarLayout>
3) In you Activity's onCreate() method add following lines -
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
UPDATE
If you want toolbar for all activities then add that XML part in respective XML file and Add JAVA part in respective Activity.
In this case you can add 2nd point (XML part) in "activity_main" and Add 3rd point (JAVA part) in "AndroidNavDrawerActivity".
This will Add toolbar as ActionBar. Hope it will help:)
Create a toolbar layout first of all: toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
android:layout_height="56dp"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#color/colorPrimary"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="center_vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
android:textSize="18sp"
android:gravity="center|center_vertical"
android:layout_weight="1"
android:textColor="#android:color/white"
android:textStyle="bold"
android:visibility="visible"
android:id="#+id/toolbar_title" />
</LinearLayout>
</android.support.v7.widget.Toolbar>
Include it in the activity you want to use:
<include
android:id="#+id/tool_bar"
layout="#layout/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
/>
Related
I want to create Multi-Level Menus in drawer Layout. My Activity.xml:-
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
</LinearLayout>
<FrameLayout
android:id="#+id/container_body"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="com.android.ShoppingMazza.activity.FragmentDrawer"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" />
Here My fragment_navigation_drawer.xml:-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white">
<android.support.v7.widget.RecyclerView
android:id="#+id/drawerList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp" />
Here My FragmentDrawer.java
public class FragmentDrawer extends Fragment {
private static String TAG = FragmentDrawer.class.getSimpleName();
private RecyclerView recyclerView;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavigationDrawerAdapter adapter;
private View containerView;
private static String[] titles = null;
private FragmentDrawerListener drawerListener;
public FragmentDrawer() {
}
public void setDrawerListener(FragmentDrawerListener listener) {
this.drawerListener = listener;
}
public static List<NavDrawerItem> getData() {
List<NavDrawerItem> data = new ArrayList<>();
// preparing navigation drawer items
for (int i = 0; i < titles.length; i++) {
NavDrawerItem navItem = new NavDrawerItem();
navItem.setTitle(titles[i]);
data.add(navItem);
}
return data;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// drawer labels
titles = getActivity().getResources().getStringArray(R.array.nav_drawer_labels);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new NavigationDrawerAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
drawerListener.onDrawerItemSelected(view, position);
mDrawerLayout.closeDrawer(containerView);
}
#Override
public void onLongClick(View view, int position) {
}
}));
return layout;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
toolbar.setAlpha(1 - slideOffset / 2);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static interface ClickListener {
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public interface FragmentDrawerListener {
public void onDrawerItemSelected(View view, int position);
}
}
Here My MainActivity.java:-
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if(id == R.id.action_search){
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case 1:
fragment = new FriendsFragment();
title = getString(R.string.title_friends);
break;
case 2:
fragment = new MessagesFragment();
title = getString(R.string.title_messages);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
}
My Current View of App below:-
but i want multi-level submenus (more than 3) in Home menu.
I am new in android developing help me. Thanks in advance
You can simply use Android TreeView Library.
Reference: https://github.com/bmelnychuk/AndroidTreeView
And if you just need three levels, you can create a threelevel custom expandable listview.
Reference: https://github.com/talhahasanzia/Three-Level-Expandable-Listview
You can use ExpandableListView instead of RecyclerView. Here is a nice tutorial to implement it.
Expandable ListView
And if you really want to use RecyclerView you can look at the following library:
Expandable RecyclerView
I created this header and i want to add it at the top of my listview in my navigation drawer the problem is that i don't know where to add it
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="178dp"
android:background="#android:color/holo_red_dark"
android:orientation="vertical"
android:weightSum="1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="56dp"
android:orientation="vertical"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
>
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:textColor="#ffffff"
android:text="Antoine Dupond"
android:textSize="14sp"
android:textStyle="bold"
/>
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:layout_marginLeft="16dp"
android:layout_marginTop="5dp"
android:text="dupond#gmail.com"
android:textSize="14sp"
android:textStyle="normal"
/>
</LinearLayout>
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="70dp"
android:layout_height="70dp"
android:src="#drawable/ic_launcher"
android:layout_marginLeft="16dp"
android:layout_marginTop="38dp"
android:id="#+id/circleView"
/>
</RelativeLayout>
My fragment with custom adapter :
public class NavigationDrawerFragment extends Fragment {
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private NavigationDrawerCallbacks mCallbacks;
private ActionBarDrawerToggle mDrawerToggle;
private MyAdapter myAdapter;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
myAdapter=new MyAdapter(getActivity());
mDrawerListView.setAdapter(myAdapter);
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(),
mDrawerLayout,
R.string.app_name,
R.string.app_name
)
{
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
public class MyAdapter extends BaseAdapter {
private Context context;
String [] socialSites ;
int [] images ={R.drawable.cafe,R.drawable.com,R.drawable.share,R.drawable.set,R.drawable.help};
public MyAdapter(Context context){
this.context=context;
socialSites = context.getResources().getStringArray(R.array.social);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = null;
if (convertView==null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=inflater.inflate(R.layout.custom_row,parent,false);
}
else{
row=convertView;
}
TextView titletexview = (TextView) row.findViewById(R.id.textView);
ImageView titleimageview =(ImageView) row.findViewById(R.id.imageView2);
titletexview.setText(socialSites[position]);
titleimageview.setImageResource(images[position]);
return row;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public Object getItem(int position) {
return socialSites[position];
}
#Override
public int getCount() {
return socialSites.length;
}
}
}
My mainactivity :
public class Nav extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment obj= null;
ListFragment listfragment = null;
switch (position) {
case 0:
listfragment= new F1_fr();
break;
case 1:
obj= new F6_fr();
break;
case 2:
obj= new F3_fr();
break;
case 3:
obj= new F4_fr();
break;
case 4:
obj= new F5_fr();
break;
}
if (obj != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, obj)
.commit();
}
else if (listfragment != null) {
// do stuff if its a listfragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, listfragment)
.commit();
}
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
case 4:
mTitle = getString(R.string.title_section4);
break;
case 5:
mTitle = getString(R.string.title_section5);
break;
case 6:
mTitle = getString(R.string.title_section6);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
/*#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.nav, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
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 = inflater.inflate(R.layout.fragment_nav, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((Nav) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
and the layout :
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:choiceMode="singleChoice"
android:divider="#android:color/transparent" android:dividerHeight="0dp"
android:background="#ffe7e7e7"
tools:context="com.example.gweltaz.coffy3.NavigationDrawerFragment"
/>
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context="com.example.gweltaz.coffy3.Nav">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout android:id="#+id/container" android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead. -->
<!-- The drawer is given a fixed width in dp and extends the full height of
the container. -->
<fragment android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width" android:layout_height="match_parent"
android:layout_gravity="start"
android:name="com.example.gweltaz.coffy3.NavigationDrawerFragment"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
Inflate the layout and add it as a header to the ListView.
In onCreateView:
View header = inflater.inflate(R.layout.header, mDrawerListView, false);
mDrawerListView.addHeaderView(header, null);
I have implemented the Navigation Drawer into my new app. But I cannot get the App name from ActionBar to toggle the Navigation Drawer. However, when I drag the navigation drawer, the ActionBar respond to this action by changing to an arrow.
Here is my code:
services_activity_main.xml
<LinearLayout
android:orientation="vertical"
android:id="#+id/container_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/title_bar_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
<LinearLayout
android:id="#+id/contents_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp">
</LinearLayout>
<LinearLayout
android:id="#+id/navigation_bar_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
</LinearLayout>
<FrameLayout
android:id="#+id/services_navigation_drawer_layout"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start">
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
services_fragment_navigation_drawer.xml
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/services_navigation_drawer_gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
android:choiceMode="multipleChoice"
android:focusable="true"
android:focusableInTouchMode="true"
android:background="#EEE" />
MainActivity.java
public class MainActivity
extends Activity
implements BaseControllerFragment.ControllerCallbacks,
ServicesNavigationDrawerFragment.NavigationDrawerCallbacks {
public final static String TAG = "MainActivity";
LinearLayout titleBarLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.services_activity_main);
titleBarLayout = (LinearLayout) findViewById(R.id.title_bar_layout);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().add(R.id.services_navigation_drawer_layout,
new ServicesNavigationDrawerFragment(),
TAG + "." + ServicesNavigationDrawerFragment.TAG).commit();
}
#Override
public void updateTitleBar(View view) {
titleBarLayout.removeAllViews();
titleBarLayout.addView(view);
titleBarLayout.invalidate();
}
#Override
public void onNavigationDrawerItemSelected(int position) {
switch (position) {
case 0:
replaceContainerContents(new BuildLicenseControllerFragment());
return;
case 1:
replaceContainerContents(new BuildLicenseControllerFragment());
return;
}
}
private void replaceContainerContents(BaseControllerFragment controllerFragment) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.contents_layout,
controllerFragment,
TAG + "." + controllerFragment.TAG).commit();
}
}
ServicesNavigationDrawerFragment.java
public class ServicesNavigationDrawerFragment extends Fragment {
public final static String TAG = "ServicesNavigationDrawerFragment";
String[] titles = {
"String 1", // 0
"String 2" // 1
};
int[] images = {
R.drawable.service_build_license,
R.drawable.service_build_license
};
private final static String STATE_SELECTED_POSITION = "SELECTED_POSITION";
private final static String PREF_USER_LEARNED_DRAWER = "USER_LEARNED_DRAWER";
private int selectedPosition = 0;
private boolean fromSavedInstance;
private boolean userLearnedDrawer;
GridView drawerGridView;
DrawerLayout drawerLayout;
FrameLayout navigationDrawerLayout;
ActionBarDrawerToggle drawerToggle;
private NavigationDrawerCallbacks callbacks;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
userLearnedDrawer = sharedPreferences.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if(savedInstanceState != null) {
selectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
fromSavedInstance = true;
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
drawerGridView = (GridView) inflater.inflate(R.layout.services_fragment_navigation_drawer, container, false);
drawerGridView.setAdapter(new ServicesAdapter(titles, images));
drawerGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
return drawerGridView;
}
#Override
public void onAttach(final Activity activity) {
super.onAttach(activity);
try {
callbacks = (NavigationDrawerCallbacks) activity;
drawerLayout = (DrawerLayout) activity.findViewById(R.id.activity_services_drawer_layout);
navigationDrawerLayout = (FrameLayout) activity.findViewById(R.id.services_navigation_drawer_layout);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
drawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, R.string.app_name, R.string.app_name) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
Log.i(TAG, "Drawer Closed!");
if (!isAdded()) {
return;
}
// activity.invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
Log.i(TAG, "Drawer Opened!");
if (!isAdded()) {
return;
}
if( ! userLearnedDrawer) {
userLearnedDrawer = true;
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
sharedPreferences.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
// activity.invalidateOptionsMenu();
}
};
if( ! userLearnedDrawer && ! fromSavedInstance) {
drawerLayout.openDrawer(navigationDrawerLayout);
}
drawerLayout.post(new Runnable() {
#Override
public void run() {
drawerToggle.syncState();
}
});
drawerLayout.setDrawerListener(drawerToggle);
} catch(ClassCastException e) {
throw new ClassCastException(activity.getClass() + " must implements NavigationDrawerCallbacks interface.");
}
}
private ActionBar getActionBar() {
return getActivity().getActionBar();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, selectedPosition);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
private void selectItem(int position) {
selectedPosition = position;
if(drawerGridView != null) {
drawerGridView.setItemChecked(position, true);
}
if(drawerLayout != null) {
drawerLayout.closeDrawer(navigationDrawerLayout);
}
if(callbacks != null) {
callbacks.onNavigationDrawerItemSelected(position);
}
}
private class ServicesAdapter extends BaseAdapter {
public final static String TAG = "ServicesAdapter";
private Context context;
private LayoutInflater inflater;
private String[] titles;
private int[] images;
private ServicesAdapter(String[] titles, int[] images) {
if(titles.length != images.length) {
throw new RuntimeException("You Must Provide Same Number of Titles and Images.");
}
context = getActivity();
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.titles = titles;
this.images = images;
}
#Override
public int getCount() {
return images.length;
}
#Override
public Object getItem(int position) {
return titles[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView textView = null;
if(convertView != null) {
textView = (TextView) convertView;
} else {
textView = (TextView) inflater.inflate(R.layout.services_layout_drawer_item, parent, false);
}
Log.i(TAG, textView.getCompoundDrawables()[1].getBounds().toString());
Drawable drawable = context.getResources().getDrawable(images[position]);
drawable.setBounds(new Rect(0, 0, 128, 128));
textView.setText(titles[position]);
textView.setCompoundDrawables(null, drawable, null, null);
return textView;
}
}
public interface NavigationDrawerCallbacks {
public void onNavigationDrawerItemSelected(int position);
}
}
You shouldn't handle your navigation drawer from fragment.
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
drawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, R.string.app_name, R.string.app_name) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
Log.i(TAG, "Drawer Closed!");
if (!isAdded()) {
return;
}
// activity.invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
Log.i(TAG, "Drawer Opened!");
if (!isAdded()) {
return;
}
if( ! userLearnedDrawer) {
userLearnedDrawer = true;
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
sharedPreferences.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
// activity.invalidateOptionsMenu();
}
};
if( ! userLearnedDrawer && ! fromSavedInstance) {
drawerLayout.openDrawer(navigationDrawerLayout);
}
drawerLayout.post(new Runnable() {
#Override
public void run() {
drawerToggle.syncState();
}
});
drawerLayout.setDrawerListener(drawerToggle);
} catch(ClassCastException e) {
throw new ClassCastException(activity.getClass() + " must implements NavigationDrawerCallbacks interface.");
}
}
private ActionBar getActionBar() {
return getActivity().getActionBar();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, selectedPosition);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}a
Shift above code from fragment to your MAinActivity.java
Make sure you have everything on your drawerToggle like follows
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
I have a navigation Drawer in my App. If i select a particular item and slide the navigation drawer. The Fragment overlaps the navigation Drawer.
I Tried to add popBackStackImmediate(); But it is of no use. This is how it looks like
Activity
public class Activity extends MainActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public void onNavigationDrawerItemSelected(int position)
{
// TODO Auto-generated method stub
if (position == 1)
{
HomeFragment Frag = new HomeFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.container, Frag);
transaction.commit();
}
else if (position == 2)
{
}
}
public void onDrawerOpened(View drawerview)
{
getFragmentManager().popBackStackImmediate();
}
Navigation Fragment
public class NavigationDrawerFragment extends Fragment implements NavigationDrawerCallbacks
{
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private static final String PREFERENCES_FILE = "my_app_settings";
private NavigationDrawerCallbacks mCallbacks;
private RecyclerView mDrawerList;
private View mFragmentContainerView;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mActionBarDrawerToggle;
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
private int mCurrentSelectedPosition;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
mDrawerList = (RecyclerView) view.findViewById(R.id.drawerList);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mDrawerList.setLayoutManager(layoutManager);
mDrawerList.setHasFixedSize(true);
final List<NavigationItem> navigationItems = getMenu();
NavigationDrawerAdapter adapter = new NavigationDrawerAdapter(navigationItems);
adapter.setNavigationDrawerCallbacks(this);
mDrawerList.setAdapter(adapter);
selectItem(mCurrentSelectedPosition);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mUserLearnedDrawer = Boolean.valueOf(readSharedSetting(getActivity(), PREF_USER_LEARNED_DRAWER, "false"));
if (savedInstanceState != null)
{
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try
{
mCallbacks = (NavigationDrawerCallbacks) activity;
}
catch (ClassCastException e)
{
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
public ActionBarDrawerToggle getActionBarDrawerToggle()
{
return mActionBarDrawerToggle;
}
public void setActionBarDrawerToggle(ActionBarDrawerToggle actionBarDrawerToggle)
{
mActionBarDrawerToggle = actionBarDrawerToggle;
}
public void setup(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar)
{
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mActionBarDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close)
{
#Override
public void onDrawerClosed(View drawerView)
{
super.onDrawerClosed(drawerView);
if (!isAdded())
return;
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView)
{
super.onDrawerOpened(drawerView);
if (!isAdded())
return;
if (!mUserLearnedDrawer)
{
mUserLearnedDrawer = true;
saveSharedSetting(getActivity(), PREF_USER_LEARNED_DRAWER, "true");
}
getActivity().invalidateOptionsMenu();
}
};
if (!mUserLearnedDrawer && !mFromSavedInstanceState)
mDrawerLayout.openDrawer(mFragmentContainerView);
mDrawerLayout.post(new Runnable()
{
#Override
public void run()
{
mActionBarDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
}
public void openDrawer()
{
mDrawerLayout.openDrawer(mFragmentContainerView);
}
public void closeDrawer()
{
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
#Override
public void onDetach()
{
super.onDetach();
mCallbacks = null;
}
public List<NavigationItem> getMenu()
{
List<NavigationItem> items = new ArrayList<NavigationItem>();
items.add(new NavigationItem("Home", getResources().getDrawable(R.drawable.play)));
items.add(new NavigationItem("News", getResources().getDrawable(R.drawable.play)));
items.add(new NavigationItem("Videos", getResources().getDrawable(R.drawable.play)));
items.add(new NavigationItem("Playlist", getResources().getDrawable(R.drawable.play)));
return items;
}
void selectItem(int position)
{
mCurrentSelectedPosition = position;
if (mDrawerLayout != null)
{
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null)
{
mCallbacks.onNavigationDrawerItemSelected(position);
}
((NavigationDrawerAdapter) mDrawerList.getAdapter()).selectPosition(position);
}
public boolean isDrawerOpen()
{
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onNavigationDrawerItemSelected(int position)
{
mCallbacks.onNavigationDrawerItemSelected(position);
selectItem(position);
}
public DrawerLayout getDrawerLayout()
{
return mDrawerLayout;
}
public void setDrawerLayout(DrawerLayout drawerLayout)
{
mDrawerLayout = drawerLayout;
}
}
Activity Layout
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="#+id/toolbar_actionbar"
layout="#layout/toolbar_default"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar_actionbar">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<!-- android:layout_marginTop="?android:attr/actionBarSize"-->
<fragment
android:id="#+id/fragment_drawer"
android:name="com.RemoteIt.client.activity.drawer.NavigationDrawerFragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"/>
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
HomeFragment
public class HomeFragment extends Fragment
{
public HomeFragment()
{}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{ View v = inflater.inflate(R.layout.home, container, false);
int redActionButtonSize = getResources().getDimensionPixelSize(R.dimen.red_action_button_size);
int redActionButtonMargin = getResources().getDimensionPixelOffset(R.dimen.action_button_margin);
int redActionButtonContentSize = getResources().getDimensionPixelSize(R.dimen.red_action_button_content_size);
int redActionButtonContentMargin = getResources().getDimensionPixelSize(R.dimen.red_action_button_content_margin);
int redActionMenuRadius = getResources().getDimensionPixelSize(R.dimen.red_action_menu_radius);
int blueSubActionButtonSize = getResources().getDimensionPixelSize(R.dimen.blue_sub_action_button_size);
int blueSubActionButtonContentMargin = getResources().getDimensionPixelSize(R.dimen.blue_sub_action_button_content_margin);
ImageView fabIconStar = new ImageView(getActivity());
fabIconStar.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_important));
FloatingActionButton.LayoutParams starParams = new FloatingActionButton.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
starParams.setMargins(redActionButtonMargin, redActionButtonMargin, redActionButtonMargin, redActionButtonMargin);
fabIconStar.setLayoutParams(starParams);
FloatingActionButton.LayoutParams fabIconStarParams = new FloatingActionButton.LayoutParams(redActionButtonContentSize, redActionButtonContentSize);
fabIconStarParams.setMargins(redActionButtonContentMargin, redActionButtonContentMargin, redActionButtonContentMargin, redActionButtonContentMargin);
FloatingActionButton leftCenterButton = new FloatingActionButton.Builder(getActivity()).setContentView(fabIconStar, fabIconStarParams).setBackgroundDrawable(R.drawable.button_action_red_selector).setPosition(FloatingActionButton.POSITION_TOP_CENTER).setLayoutParams(starParams).build();
// Set up customized SubActionButtons for the right center menu
SubActionButton.Builder lCSubBuilder = new SubActionButton.Builder(getActivity());
lCSubBuilder.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_action_blue_selector));
FrameLayout.LayoutParams blueContentParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
blueContentParams.setMargins(blueSubActionButtonContentMargin, blueSubActionButtonContentMargin, blueSubActionButtonContentMargin, blueSubActionButtonContentMargin);
lCSubBuilder.setLayoutParams(blueContentParams);
// Set custom layout params
FrameLayout.LayoutParams blueParams = new FrameLayout.LayoutParams(blueSubActionButtonSize, blueSubActionButtonSize);
lCSubBuilder.setLayoutParams(blueParams);
ImageView lcIcon1 = new ImageView(getActivity());
ImageView lcIcon2 = new ImageView(getActivity());
ImageView lcIcon3 = new ImageView(getActivity());
ImageView lcIcon4 = new ImageView(getActivity());
ImageView lcIcon5 = new ImageView(getActivity());
ImageView lcIcon6 = new ImageView(getActivity());
ImageView lcIcon7 = new ImageView(getActivity());
ImageView lcIcon8 = new ImageView(getActivity());
ImageView lcIcon9 = new ImageView(getActivity());
lcIcon1.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_camera));
lcIcon2.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_picture));
lcIcon3.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_video));
lcIcon4.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_location_found));
lcIcon5.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_headphones));
lcIcon6.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_camera));
lcIcon7.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_picture));
lcIcon8.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_video));
lcIcon9.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_location_found));
// Build another menu with custom options
FloatingActionMenu leftCenterMenu = new FloatingActionMenu.Builder(getActivity()).addSubActionView(lCSubBuilder.setContentView(lcIcon1, blueContentParams).build()).addSubActionView(lCSubBuilder.setContentView(lcIcon2, blueContentParams).build()).addSubActionView(lCSubBuilder.setContentView(lcIcon3, blueContentParams).build()).addSubActionView(lCSubBuilder.setContentView(lcIcon4, blueContentParams).build()).addSubActionView(lCSubBuilder.setContentView(lcIcon5, blueContentParams).build())
.addSubActionView(lCSubBuilder.setContentView(lcIcon6, blueContentParams).build()).addSubActionView(lCSubBuilder.setContentView(lcIcon7, blueContentParams).build()).addSubActionView(lCSubBuilder.setContentView(lcIcon8, blueContentParams).build()).addSubActionView(lCSubBuilder.setContentView(lcIcon9, blueContentParams).build()).setRadius(redActionMenuRadius).setStartAngle(0).setEndAngle(360).attachTo(leftCenterButton).build();
return v;
}
}
The following changes were made to the FloatingActionButton and FloatingActionMenu classes to allow a specific ViewGroup to be set as the container for both. Tests were made with a similar but simpler version of the code you've posted, so you may need to make adjustments to your setup parameters.
The library code assumes that the Button and Menu are to appear on top of an Activity's content View, and everything therein. The addition of a container ViewGroup member in the FloatingActionButton class allows us to specify a child ViewGroup to be the parent instead. Please note that the following changes will only work if a FloatingActionButton is used with the Menu.
The additions to the FloatingActionButton class:
public class FloatingActionButton extends FrameLayout {
...
private ViewGroup containerView;
...
public FloatingActionButton(Activity activity,
LayoutParams layoutParams,
int theme,
Drawable backgroundDrawable,
int position,
View contentView,
FrameLayout.LayoutParams contentParams
// Note the addition of the following
// constructor parameter here
, ViewGroup containerView) {
...
setClickable(true);
// This line is new. The rest of the constructor is the same.
this.containerView = containerView;
attach(layoutParams);
}
...
public View getActivityContentView() {
if(containerView == null) {
return ((Activity)getContext())
.getWindow().getDecorView().findViewById(android.R.id.content);
} else {
return containerView;
}
}
public ViewGroup getContainerView() {
return containerView;
}
// The following setter is not strictly necessary, but may be of use
// if you want to toggle the Button's and Menu's z-order placement
public void setContainerView(ViewGroup containerView) {
this.containerView = containerView;
}
...
public static class Builder {
...
private ViewGroup containerView;
...
public Builder setContainerView(ViewGroup containerView) {
this.containerView = containerView;
return this;
}
public FloatingActionButton build() {
return new FloatingActionButton(activity,
layoutParams,
theme,
backgroundDrawable,
position,
contentView,
contentParams,
// New argument
containerView);
}
}
...
}
And the changes to the FloatingActionMenu class:
public class FloatingActionMenu {
...
public View getActivityContentView() {
if(mainActionView instanceof FloatingActionButton &&
((FloatingActionButton) mainActionView).getContainerView() != null) {
return ((FloatingActionButton) mainActionView).getContainerView();
} else {
return ((Activity)mainActionView.getContext())
.getWindow().getDecorView().findViewById(android.R.id.content);
}
}
...
}
Then, in the Fragment's onCreateView() method, we need to add a call the new setContainerView() method of the FloatingActionButton.Builder class.
public class HomeFragment extends Fragment {
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
...
FloatingActionButton leftCenterButton = new FloatingActionButton.Builder(getActivity())
.setContentView(fabIconStar, null)
.setBackgroundDrawable(R.drawable.ic_launcher)
.setPosition(FloatingActionButton.POSITION_TOP_CENTER)
.setLayoutParams(starParams)
// The new method call is added here
.setContainerView(container)
.build();
...
}
...
}
Please replace the below line of code
transaction.replace(R.id.container, Frag);
with
transaction.replace(R.id.content_frame, Frag);
I had this overlapping issue once due to android.R.id.content and i replaced it with R.id.content_frame which solved my issue.
But i see in your code that you have used a different container view ID, but this should work though.
I am attempting to use Kanytu's android-material-drawer-template to implement a Navigation Drawer that meets Google's material design guidelines. The issue I'm facing is: Upon selecting a fragment to transition to from the navigation drawer, the selected fragment will successfully replace the current fragment within the 'container' FrameLayout. However, the HomeAsUp Indicater will display a "Back" navigation arrow in the Toolbar, rather than the Hamburger Icon needed to open the Navigation Drawer.
From what I can gather, this is due to the ActionBarDrawerToggle becoming out of sync when the fragments are being swapped. Assuming this to be the issue (I'm open for suggestions), how could I call .syncState() within the NavigationActivity fragments on the current ActionBarDrawerToggle?
public class NavigationActivity extends ActionBarActivity implements NavigationDrawerCallbacks {
private Toolbar mToolbar;
private NavigationDrawerFragment mNavigationDrawerFragment;
#Override
protected void onCreate( #Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.fragment_drawer);
mNavigationDrawerFragment.setup(R.id.fragment_drawer, (DrawerLayout) findViewById(R.id.drawer), mToolbar);
if (findViewById(R.id.container) != null) {
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Toast.makeText(this, "Menu item selected -> " + position, Toast.LENGTH_SHORT).show();
if (position == 0) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.container, new UserFragment());
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle(getString(R.string.user_profile_title));
}
}
if (position == 1) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.container, new TeamFragment());
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle(getString(R.string.team_profile_title));
}
}
if (position == 2) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.container, new ExploreFragment());
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle(getString(R.string.explore_title));
}
}
}
#Override
public void onBackPressed() {
if (mNavigationDrawerFragment.isDrawerOpen())
mNavigationDrawerFragment.closeDrawer();
else
super.onBackPressed();
}
}
public class NavigationDrawerAdapter extends RecyclerView.Adapter<NavigationDrawerAdapter.ViewHolder> {
private List<NavigationItem> mData;
private NavigationDrawerCallbacks mNavigationDrawerCallbacks;
private int mSelectedPosition;
private int mTouchedPosition;
private boolean isClick = false;
public NavigationDrawerAdapter(List<NavigationItem> data) {
mData = data;
}
public NavigationDrawerCallbacks getNavigationDrawerCallbacks() {
return mNavigationDrawerCallbacks;
}
public void setNavigationDrawerCallbacks(NavigationDrawerCallbacks navigationDrawerCallbacks) {
mNavigationDrawerCallbacks = navigationDrawerCallbacks;
}
#NotNull
#Override
public NavigationDrawerAdapter.ViewHolder onCreateViewHolder( #NotNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.drawer_row, viewGroup, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder( #NotNull NavigationDrawerAdapter.ViewHolder viewHolder, final int i) {
viewHolder.textView.setText(mData.get(i).getText());
viewHolder.textView.setCompoundDrawablesWithIntrinsicBounds(mData.get(i).getDrawable(), null, null, null);
viewHolder.itemView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, #NotNull MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchPosition(i);
return false;
case MotionEvent.ACTION_CANCEL:
touchPosition(-1);
return false;
case MotionEvent.ACTION_MOVE:
return false;
case MotionEvent.ACTION_UP:
touchPosition(-1);
return false;
}
return true;
}
}
);
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mNavigationDrawerCallbacks != null)
mNavigationDrawerCallbacks.onNavigationDrawerItemSelected(i);
}
}
);
//TODO: selected menu position, change layout accordingly
if (mSelectedPosition == i || mTouchedPosition == i) {
viewHolder.itemView.setBackgroundColor(viewHolder.itemView.getContext().getResources().getColor(R.color.nav_selected));
} else {
viewHolder.itemView.setBackgroundColor(Color.TRANSPARENT);
}
}
private void touchPosition(int position) {
int lastPosition = mTouchedPosition;
mTouchedPosition = position;
if (lastPosition >= 0)
notifyItemChanged(lastPosition);
if (position >= 0)
notifyItemChanged(position);
}
public void selectPosition(int position) {
int lastPosition = mSelectedPosition;
mSelectedPosition = position;
notifyItemChanged(lastPosition);
notifyItemChanged(position);
}
#Override
public int getItemCount() {
return mData != null ? mData.size() : 0;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView textView;
public ViewHolder( #NotNull View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.item_name);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_navigation_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="#+id/toolbar_actionbar"
layout="#layout/toolbar_actionbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar_actionbar">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<!-- android:layout_marginTop="?android:attr/actionBarSize"-->
<fragment
android:id="#+id/fragment_drawer"
android:name="com.example.appnamehere.NavigationDrawerFragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
public class NavigationDrawerFragment extends Fragment implements NavigationDrawerCallbacks {
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private static final String PREFERENCES_FILE = "my_app_settings"; //TODO: change this to your file
#Nullable
private NavigationDrawerCallbacks mCallbacks;
private RecyclerView mDrawerList;
private View mFragmentContainerView;
private DrawerLayout mDrawerLayout;
public ActionBarDrawerToggle mActionBarDrawerToggle;
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
private int mCurrentSelectedPosition;
#Override
public View onCreateView( #NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
mDrawerList = (RecyclerView) view.findViewById(R.id.drawerList);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mDrawerList.setLayoutManager(layoutManager);
mDrawerList.setHasFixedSize(true);
final List<NavigationItem> navigationItems = getMenu();
NavigationDrawerAdapter adapter = new NavigationDrawerAdapter(navigationItems);
adapter.setNavigationDrawerCallbacks(this);
mDrawerList.setAdapter(adapter);
selectItem(mCurrentSelectedPosition);
return view;
}
#Override
public void onCreate( #Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUserLearnedDrawer = Boolean.valueOf(readSharedSetting(getActivity(), PREF_USER_LEARNED_DRAWER, "false"));
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
public ActionBarDrawerToggle getActionBarDrawerToggle() {
return mActionBarDrawerToggle;
}
public void setActionBarDrawerToggle(ActionBarDrawerToggle actionBarDrawerToggle) {
mActionBarDrawerToggle = actionBarDrawerToggle;
}
public void setup(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mActionBarDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) return;
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) return;
if (!mUserLearnedDrawer) {
mUserLearnedDrawer = true;
saveSharedSetting(getActivity(), PREF_USER_LEARNED_DRAWER, "true");
}
getActivity().invalidateOptionsMenu();
}
};
if (!mUserLearnedDrawer && !mFromSavedInstanceState)
mDrawerLayout.openDrawer(mFragmentContainerView);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mActionBarDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
}
public void openDrawer() {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
public void closeDrawer() {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#NotNull
public List<NavigationItem> getMenu() {
List<NavigationItem> items = new ArrayList<NavigationItem>();
items.add(new NavigationItem("User Profile", getResources().getDrawable(R.drawable.ic_drawer_my_profile), UserFragment.class));
items.add(new NavigationItem("Team Profile", getResources().getDrawable(R.drawable.ic_drawer_my_team), TeamFragment.class));
items.add(new NavigationItem("Explore", getResources().getDrawable(R.drawable.ic_drawer_explore), ExploreFragment.class));
return items;
}
void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
} else {
return;
}
((NavigationDrawerAdapter) mDrawerList.getAdapter()).selectPosition(position);
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onSaveInstanceState( #NotNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onNavigationDrawerItemSelected(int position) {
selectItem(position);
}
public DrawerLayout getDrawerLayout() {
return mDrawerLayout;
}
public void setDrawerLayout(DrawerLayout drawerLayout) {
mDrawerLayout = drawerLayout;
}
public static void saveSharedSetting( #NotNull Context ctx, String settingName, String settingValue) {
SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(settingName, settingValue);
editor.apply();
}
public static String readSharedSetting( #NotNull Context ctx, String settingName, String defaultValue) {
SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE);
return sharedPref.getString(settingName, defaultValue);
}