I have toolbar and framelayout(for fragments) in my main activity layout. I have to show the toolbar in every fragments. But the issue is each fragment has different background image that is dynamically changing. Toolbar menu icon is used for navigation drawer open and close operation. How I will handle these issue?
Before posting the code block let's first understand what are we are going to do.
1.Create a HomeActivity that holds all the fragments.
Here is the activity_home.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_home"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_home"
app:menu="#menu/activity_home_drawer" />
</android.support.v4.widget.DrawerLayout>
Here is the app_bar_home.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
the other xmls of navigationview -- activity_home_drawer.xml contains navigation drawer contents and nav_header_home.xml is the navigation drawer header layout.
2.Let's come to java part of the HomeActivity.java
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
private HomeBean bean;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ButterKnife.bind(this);
initListener();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//this menu contains all the common menu item actions
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
//common options bar item click here i have notifications icon common for all the fragments
#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.
switch (item.getItemId()){
case R.id.action_notifications:
AppUtils.launchActivity(HomeActivity.this, NotificationActivity.class,intentData);
return false;
default:
return super.onOptionsItemSelected(item);
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Handle navigation view item clicks here.
Fragment selectedFragment = null;
switch (item.getItemId()){
case R.id.nav_dashboard:
//you can cache this fragment in case of repeated creations
selectedFragment = new DashBoardFragment();
}
break;
}
if(selectedFragment != null){
displayFragment(selectedFragment);
DrawerLayout drawer = ButterKnife.findById(this,R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
return true;
}
private void displayFragment(Fragment fragment) {
if(fragment !=null){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
}
#Override
public void initToolBar() {}
public void setToolbar(Toolbar toolbar){
setSupportActionBar(toolbar);
setActionBarToggle(toolbar);
}
private void setActionBarToggle(Toolbar toolbar) {
DrawerLayout drawer = ButterKnife.findById(this, R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
}
#Override
public void initListener() {
NavigationView navigationView = ButterKnife.findById(this,R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//as the first item is show by default
navigationView.getMenu().getItem(0).setChecked(true);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
Now as an example let see how the fragments are written.
public class SettingsFragment extends Fragment {
#BindView(R.id.toolbar)
Toolbar toolbar;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_settings,container,false);
ButterKnife.bind(this,view);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
((HomeActivity)getActivity()).setToolbar(toolbar);
}
}
Corresponding fragment xml fragment_settings.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="Fragment Name">
<android.support.design.widget.AppBarLayout
android:id="#+id/notification_appbar"
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"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:title="#string/settings"/>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_settings" />
</android.support.design.widget.CoordinatorLayout>
the corresponding xml content_settings.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/min_widget_padding"
android:id="#+id/nsv_settings_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
// your content goes here
</<android.support.v4.widget.NestedScrollView>
I hope this gives clear picture on how to do in case if you have any other doubts please comment.
Use this code. I helped
public class MyFragment extends Fragment {
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);// To enable actionbar in fragments
super.onCreate(savedInstanceState);
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//Here it is necessary to connect the layout menu
inflater.inflate(R.menu.fragment2, menu);
super.onCreateOptionsMenu(menu, inflater);
}
}
Related
I have this menu layout "navigation_menu.xml":
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/item1"
android:title="#string/item1"/>
<item
android:id="#+id/item2"
android:title="#string/item2"/>
<item
android:id="#+id/item3"
android:title="#string/item3"/>
</menu>
My main activity layout "activity_main.xml" is this:
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".MainActivity">
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="#menu/navigation_menu"
android:layout_gravity="start">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
And this is the Java code of the main activity where I initialize the drawer:
private DrawerLayout drawer_layout;
private ActionBarDrawerToggle toggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
drawer_layout = (DrawerLayout)findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(this, drawer_layout, R
.string.open_drawer, R.string.close_drawer);
drawer_layout.addDrawerListener(toggle);
toggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ...
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (toggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
The drawer opens and closes correctly, but I don't know how to do something when an item is clicked, for example showing a log.
Does anyone know?
Thanks
Use onNavigationItemSelected() method to handle Navigation Drawer Item Click. See Below Code.
private NavigationView mNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
// ...
mNavigationView = (NavigationView) findViewById(R.id.nav_view);
mNavigationView.setNavigationItemSelectedListener(this);// you need to set Listener.
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item)
{
// mDrawer.closeDrawer(GravityCompat.START);
switch (item.getItemId()) {
case R.id.item1: {
}
break;
case R.id.item2: {
}
break;
case R.id.item3: {
}
break;
}
return true;
}
Getting wired output
When i click on TextView of Navigation Drawer click goes to fragment in back (Main Content Fragment)
Please someone help what wrong i am doing.
layout code
<LinearLayout 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:orientation="vertical">
<!-- The toolbar -->
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:title="#string/app_name" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white">
<!-- The main content view -->
<LinearLayout 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:orientation="vertical">
<include layout="#layout/content_main" />
</LinearLayout>
<!-- The navigation drawer -->
<fragment
android:id="#+id/left_drawer"
android:name="app.compiler.fragment.FragmentDrawer"
android:layout_width="320dp"
android:layout_height="match_parent"
android:layout_gravity="start"
tools:layout="#layout/fragment_drawer"
/>
</android.support.v4.widget.DrawerLayout>
Java code
public class ActivityMain extends AppCompatActivity {
DrawerLayout mDrawerLayout;
ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ide);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle= new ActionBarDrawerToggle(this, mDrawerLayout,toolbar, R.string.app_name, R.string.app_name)
{
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
FragmentMain fragmentMain = new FragmentMain();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.container, fragmentMain);
transaction.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = new MenuInflater(this);
inflater.inflate(R.menu.menu_main,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
if(mDrawerLayout.isDrawerOpen(Gravity.START | Gravity.LEFT)){
mDrawerLayout.closeDrawers();
return;
}
super.onBackPressed();
}
}
Check code output in gif image below
Make sure that everything within your left-drawer-layout is clickable. Otherwise, clicks will be passed to the underlying view, in this case to your main-content. You can do so by setting an OnClickListener to the rootview of your FragmentDrawer:
myFragmentInsideTheDrawer.getView().setOnClickListener(new OnClickListener() {
#Override
public void onClick(View pView) {
// do nothing here, just intercept click-events
}
});
In inDrawerOpen method you can use yourcontentlayout.setEnabled(false) and in onDrawerClosed method yourcontentlayout.setEnabled(true)
Hope this helps!
i am using navigation view for navigation drawer...and there are certain menu items int he drawer and when i clicked on a particular a new activity opens and i want to open navigation drawer from that activity too.. i tried one way in which i had to extends my main activity(the one having drawer) to the activity (or the second activity)...and add this in my second activity instead of setcontentview.. but the thing is my second activity xml is just above the mainactivity.xml.. i see both the activity one above the other(secondactivity above mainactivity.xml) how to just show only secondactivity with the drawer.
LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View activityView = layoutInflater.inflate(R.layout.activity_credits, null,false);
// add the custom layout of this activity to frame layout.
drawerLayout.addView(activityView);
You can achieve this task by creating one common class say BaseActivity.java and put your code of navigation drawer in this class. and extend your classes with BaseActivity.java where you want to show navigation drawer.
public class BaseActivity extends AppCompatActivity {
public Toolbar toolbar; // Declaring the Toolbar Object
ActionBarDrawerToggle mDrawerToggle;
Context context;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected boolean useToolbar() {
return true;
}
#Override
public void setContentView(int layoutResID) {
context = this;
DrawerLayout fullView = (DrawerLayout) getLayoutInflater().inflate(R.layout.drawer_main, null);
FrameLayout activityContainer = (FrameLayout) fullView.findViewById(R.id.frame);
getLayoutInflater().inflate(layoutResID, activityContainer, true);
super.setContentView(fullView);
toolbar = (Toolbar) fullView.findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
toolbar.setTitle("");
this.getSupportActionBar().setElevation(0);
getSupportActionBar().setLogo(R.drawable.ic_arrahm);
// toolbar.setLogo(R.drawable.ic_main);
if (useToolbar()) {
setSupportActionBar(toolbar);
setTitle("Places Near Me");
} else {
toolbar.setVisibility(View.GONE);
}
//Initializing NavigationView
navigationView = (NavigationView) findViewById(R.id.navigation_view);
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
case R.id.edit_profile:
return true;
case R.id.change_password:
return true;
default:
Toast.makeText(getApplicationContext(), "Work in progress", Toast.LENGTH_SHORT).show();
return true;
}
}
});
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
View header = navigationView.getHeaderView(0);
TextView tvName = (TextView) header.findViewById(R.id.name);
TextView tvEmail = (TextView) header.findViewById(R.id.email);
String name = Preferences.getDataFromStringPreferences(context,Constants.USER_DETAILS, Constants.USER_NAME);
if (name != null) {
tvName.setText(name);
}
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessay or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return mDrawerToggle.onOptionsItemSelected(item);
}
}
create drawer_main.xml layout file
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="#+id/tool_bar"
layout="#layout/toolbar" />
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/drawer">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
create toolbar.xml under layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
>
</android.support.v7.widget.Toolbar>
create drawer_header.xml layout resource file
<?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="#color/colorPrimary"
android:orientation="vertical"
android:padding="20dp"
android:weightSum="1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:orientation="vertical">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:text=""
android:textColor="#ffffff"
android:textSize="14sp"
android:textStyle="bold"
/>
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:text=""
android:textColor="#ffffff"
android:textSize="14sp"
android:textStyle="normal"
/>
</LinearLayout>
<ImageView
android:id="#+id/circleView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="16dp"
android:layout_marginTop="30dp" />
</RelativeLayout>
I've a single activity(MainActivity) which extends actionbaractivity and implements NavigationDrawer. I've setup the drawertoggle in the activity itself.
I'm creating new fragments from a fragment that was created by another fragment which is in turn created by the MainActivity. ( MainActivity -> HomeFragment ->AnotherFragment).
MainActivity.java
public class MainActivity extends ActionBarActivity implements FragmentDrawer.FragmentDrawerListener, TitleSetter, NavigationDrawerEnabler{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setHomeButtonEnabled(true);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), myToolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
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 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.
/* This function is never called even if the Up caret button is pressed!! */
if (mDrawerToggle.isDrawerIndicatorEnabled() &&
mDrawerToggle.onOptionsItemSelected(item))
return true;
switch (item.getItemId()) {
case android.R.id.home:
/*This case doesn't occur*/
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onDrawerItemSelected(View view, int position) {
mDrawerLayout.closeDrawer(containerView);
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 SomeFragment();
title = getString(R.string.title_something);
break;
case 2:
//fragment = new SomeotherFragment();
//title = getString(R.string.title_somethings);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
getSupportActionBar().setTitle(title);
}
}
#Override
public void setTitle(String title) {
getSupportActionBar().setTitle(title);
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getSupportActionBar().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();
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
enableNavigationDrawer(true);
}
#Override
public void enableNavigationDrawer(boolean isEnabled) {
if ( isEnabled ) {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerToggle.syncState();
}
else {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
mDrawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerToggle.syncState();
}
}
}
HomeFragment.java
public class HomeFragment extends Fragment implements View.OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.home, container, false);
// Inflate the layout for this fragment
fab = (FloatingActionButton) rootView.findViewById(R.id.fab);
fab.setOnClickListener(this);
((TitleSetter) getActivity()).setTitle("Home");
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.fab:
((NavigationDrawerEnabler) getActivity()).enableNavigationDrawer(false);
Fragment newFragment = new NewWord();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, newFragment);
fragmentTransaction.addToBackStack(null);
// Commit the transaction
fragmentTransaction.commit();
break;
}
}
}
AnotherFragment.java
public class NewWord extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Get item selected and deal with it
/*Not even this*/
Log.d("KEY: ", String.valueOf(item.getItemId()));
switch (item.getItemId()) {
case android.R.id.home:
/* Doesn't execute*/
Log.d("Fragment", "I'm here");
getActivity().onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.new_word, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((TitleSetter) activity).setTitle("Text");
}
Also the drawer layout
<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" >
</FrameLayout>
</LinearLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="com.calgen.wordbook.activity.FragmentDrawer"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_nav_drawer"
tools:layout="#layout/fragment_nav_drawer" />
And menu_main.xml
<menu 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"
tools:context=".MainActivity">
<item
android:id="#+id/action_search"
android:title="#string/action_search"
android:orderInCategory="100"
android:icon="#drawable/ic_action_search"
app:showAsAction="ifRoom" />
<item
android:id="#+id/action_settings"
android:title="#string/action_settings"
android:orderInCategory="100"
app:showAsAction="never" />
I actually referred this tutorial to setup navigation drawer fragment : Android Hive.
I also referred similar questions answered here on stackoverflow :
1.Switching between Android Navigation Drawer image and Up caret when using fragments
2.My problem is similiar to this : Android Navigation Drawer Show Up Indicator for Lower Level Fragments.
- I couldn't comment here as i do not have 50 reps. I implemented what was exactly told in the comments.
But still clicking on the up caret doesn't run the function onOptionItemSelected, even though i've homebutton enabled.!
I'm now adding my custom styles.xml, may be some error in this?
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyMaterialTheme" parent="MyMaterialTheme.Base"></style>
<style name="MyMaterialTheme.Base" parent="Theme.AppCompat">
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="android:activatedBackgroundIndicator">#drawable/nav_background</item>
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="android:textColorPrimary">#color/textColorPrimary</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
</resources>
Also the custom toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
local:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
local:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
SOLVED FINALLY
I figured out the problem, it is due to the custom toolbar that I used. When a custom toolbar is set up, we also have to set a listener on the up caret using the method called drawertoggler.setNaviagtionOnClickListener
In the onCreate() method of the activity we need to add the following code:
drawertoggler.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getSupportFragmentManager().popBackStackImmediate();
}
});
Other cases like OnBackPressed can be handled by setting a OnStackChangeListener in the activity and make necessary changes. It is clearly explained here :#riwnodennyk.
I'm using navigation drawer for a project, everything is working fine but one small problem, I always that arrow displayed not home button.
I tried everything found in the documentations, forums and here nothing is actually working.
What I tried so far:
mDrawerToggle.syncState();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
#Override
public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onPostCreate(savedInstanceState, persistentState);
mNavigationDrawerFragment.getmDrawerToggle().syncState();
}
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setTitle(mTitle);
NavigationDrawerFragment:
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
i have been busy making a simple app with navigation drawer..don't use template there are deprecated methods..
This is completely working.. i created this example.. try this..
your MainActivity
public class MainActivity extends ActionBarActivity {
Toolbar toolbar;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.app_toolbar);
setSupportActionBar(toolbar);
Profile profile = (Profile) getSupportFragmentManager().findFragmentById(R.id.profileFragmentInMain);
profile.setUp((DrawerLayout) findViewById(R.id.drawer),toolbar);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
This is your Fragment..
public class Profile extends Fragment {
ActionBarDrawerToggle drawerToggle;
DrawerLayout mDrawerLayout;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.profile, container, false);
return view;
}
public void setUp(DrawerLayout drawerLayout, Toolbar toolbar) {
mDrawerLayout = drawerLayout;
drawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.open, R.string.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 boolean onOptionsItemSelected(MenuItem item) {
if (item != null && item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(Gravity.RIGHT)) {
mDrawerLayout.closeDrawer(Gravity.RIGHT);
} else {
mDrawerLayout.openDrawer(Gravity.RIGHT);
}
return true;
}
return false;
}
};
mDrawerLayout.setDrawerListener(drawerToggle);
mDrawerLayout.post(new Runnable(){
#Override
public void run(){
drawerToggle.syncState();
}
});
}
}
this is all in classes..
now xml layouts..
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:id="#+id/drawer"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<include
android:id="#+id/app_toolbar"
layout="#layout/toolbar"/>
</LinearLayout>
<fragment
android:id="#+id/profileFragmentInMain"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/profile"
android:name="com.example.ajay.myapplication.Profile"
tools:layout="#layout/profile"/>
</android.support.v4.widget.DrawerLayout>
your profile.xml
<?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"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:theme="#android:style/Theme.Holo.Light.DialogWhenLarge.NoActionBar">
</LinearLayout>
your toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
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="wrap_content"
android:id="#+id/app_toolbar" />
previews :
open the drawer
closed drawer
Additional Info : I have added toolbar which is Material Design implemetation of ActionBar. Its latest way to create Actionbar. You can use that. just in case, select Theme with NoActionbBar in your styles.xml file.
So I finally found the solution. I just took of this R.drawable.ic_drawer from:
drawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, R.drawable.ic_drawer, R.string.open, R.string.close);
And it worked like a charm.