I added a navigation drawer to my toolbar and added the toolbar to my HomePage Activity. The Drawer seems to be working fine but only pulls out when I slide my finger below the hamburger icon. Otherwise, if I simply click on the icon nothing happens. Does anybody know why? I watched the following tutorial and ideally when the hamburger icon is clicked, the drawer should come out: https://www.youtube.com/watch?v=Lfc1q1dFB3E
Is there an onClick attribute that I'm missing? Here is my code:
public class HomePage extends AppCompatActivity implements View.OnClickListener {
private DrawerLayout drawerLayout;
private ListView drawerList;
private ActionBarDrawerToggle drawerToggle;
String[] drawerListItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolBarHome);
drawerLayout = (DrawerLayout)findViewById(R.id.homePageDrawer);
drawerList = (ListView)findViewById(R.id.homePageList);
drawerListItems = getResources().getStringArray(R.array.activities);
drawerList.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,drawerListItems));
drawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0: {
Intent i = new Intent(HomePage.this, HomePage.class);
startActivity(i);
break;
}
case 1: {
Intent i = new Intent(HomePage.this, Allergy.class);
startActivity(i);
break;
}
}
drawerLayout.closeDrawer(drawerList);
}
});
drawerToggle = new ActionBarDrawerToggle(this,drawerLayout,myToolbar,R.string.drawer_open,R.string.drawer_close)
{
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
syncState();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
syncState();
}
};
drawerLayout.setDrawerListener(drawerToggle);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
drawerToggle.syncState();
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.home:{
if (drawerLayout.isDrawerOpen(drawerList)){
drawerLayout.closeDrawer(drawerList);
}else{
drawerLayout.openDrawer(drawerList);
}
return true;
}
default:return super.onOptionsItemSelected(item);
}
}
Here is the XML layout. I have one ImageView on my Homepage Activity. When the NavigationDrawer pulls out, I need it to cover the existing ImageView, so I placed it within a relative layout within my drawerlayout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:background="#drawable/boardlayered"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolBarHome"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary">
</android.support.v7.widget.Toolbar>
<android.support.v4.widget.DrawerLayout
android:id="#+id/homePageDrawer"
android:layout_below="#+id/toolBarHome"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/dogPic"
android:background="#drawable/happy_dog"
android:layout_width="175dp"
android:layout_height="200dp"
android:layout_alignParentBottom="true"
android:layout_marginLeft="20dp" />
</RelativeLayout>
<ListView
android:id="#+id/homePageList"
android:background="#android:color/white"
android:layout_gravity="start"
android:layout_width="305dp"
android:layout_height="match_parent"></ListView>
</android.support.v4.widget.DrawerLayout>
Found it. The issue is in this piece of code, which is directly responsible for the hamburger icon to perform an action:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.home:{
if (drawerLayout.isDrawerOpen(drawerList)){
drawerLayout.closeDrawer(drawerList);
}else{
drawerLayout.openDrawer(drawerList);
}
return true;
}
default:return super.onOptionsItemSelected(item);
}}
Specifically
case R.id.home:
Should be
case android.R.id.home:
This latter case syntax is what works
I think the problem here is with the lines:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
It seems this will try to use your toggle button as an 'up' navigation button instead, if you're trying to use the hamburger button to open and close your drawer you can remove these lines.
Related
I am developing an Android app about music. In this app, I have two fragments: PopFragment e GenresFragment.
In the XML file of PopFragment called fragment_pop.xml, I have toolbar with a back arrow that goes back to GenresFragment.
My toolbar code is this:
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
>
<include
android:layout_height="wrap_content"
android:layout_width="match_parent"
layout="#layout/toolbar_layout"
/>
</android.support.design.widget.AppBarLayout>
<ImageButton
android:id="#+id/arrowPop"
android:layout_width="54dp"
android:layout_height="wrap_content"
android:src="#drawable/ic_arrow_back_black_24dp"
style="?android:attr/borderlessButtonStyle"
/>
In the Java file of PopFragment called PopActivity, I have some code but it's not working.
I have this code:
public class PopActivity extends AppCompatActivity implements View.OnClickListener {
public PopActivity() {
// Required empty public constructor
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pop);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
ImageButton backBtn = (ImageButton)findViewById(R.id.arrowPop);
}
#Override
public void onClick (View view) {
Intent i = new Intent();
switch (view.getId()) {
case R.id.arrowPop:
break;
}
}
Can you help me please?
Thank you
Try something like:
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
inflater.inflate(R.menu.your_menu, menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
getActivity().onBackPressed();
break;
}
}
return true;
}
You generally don't need to add your own arrow icon, the Toolbar should be able to handle it for you.
if(shouldShowArrow()) {
drawerLayout.setDrawerLockMode(LOCK_MODE_LOCKED_CLOSED, GravityCompat.START);
drawerToggle.setDrawerIndicatorEnabled(false);
MyActivity.this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} else { // hamburglar icon
drawerLayout.setDrawerLockMode(LOCK_MODE_UNLOCKED, GravityCompat.START);
MyActivity.this.getSupportActionBar().setDisplayHomeAsUpEnabled(false);
drawerToggle.setDrawerIndicatorEnabled(true);
}
drawerToggle.syncState();
And then you can define what happens when you click the arrow
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
drawerToggle = new ActionBarDrawerToggle(MyActivity.this, drawerLayout, toolbar, R.string.open, R.string.close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
MyActivity.this.supportInvalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
MyActivity.this.supportInvalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(drawerToggle);
drawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// what to do when you click the arrow
}
});
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setHomeButtonEnabled(true);
}
#Override
protected void onPostCreate(Bundle bundle) {
super.onPostCreate(bundle);
drawerToggle.syncState();
}
#Override
protected void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
Use the following code as a quick fix, which mimics the back button being pressed.
switch (view.getId()) {
case R.id.arrowPop:
onBackPressed();
break;
}
Using this code, you shouldn't have to define the back button in the toolbar yourself, Android will handle it.
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Then when you click the back button, Android will call onBackPressed() for you.
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!
Im using Android Studio 1.2
The icon drawer in actionbar is give me an error when I click then but is work fine If I open it sliding with the hand from the left to the rigth.
this is my layout where I have my drawer list from the left; the list of options is in listView "mimenu"
<RelativeLayout xmlns:android="xxxxxx"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingTop="0dp"
android:paddingBottom="0dp"
android:background="#ffffff"
tools:context="xxxx">
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffffff">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<ListView
android:id="#+id/listaxx"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
></ListView>
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_gravity="left"
>
<ListView
android:id="#+id/mimenu"
android:layout_width="match_parent"
android:layout_below="#+id/profileBox"
android:choiceMode="singleChoice"
android:layout_height="match_parent"
android:background="#ffffff"
android:divider="#eee"
android:dividerHeight="1dp"
/>
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
In my class java
public class ListaPat extends Activity {
public ArrayList<Pat> lstPat= new ArrayList<Pat>();
private Pat_Adaptador adaptador;
private LinearLayout linearLayout;
ArrayAdapter<CharSequence> navigationDrawerAdapter;
ListView leftDrawerList;
String[] leftSliderData = new String[]{"test1","test2"};
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_patx);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
leftDrawerList = (ListView)findViewById(R.id.mimenu);
navigationDrawerAdapter= new ArrayAdapter<CharSequence>( ListaPat .this, android.R.layout.simple_list_item_1, leftSliderData);
leftDrawerList.setAdapter(navigationDrawerAdapter);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
RellenarNoticias();
InicializarLista();
mDrawerLayout.setDrawerListener(mDrawerToggle);
getActionBar().setDisplayShowHomeEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle.syncState();
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(mDrawerLayout.isDrawerOpen(leftDrawerList)) {
mDrawerLayout.closeDrawer(leftDrawerList);
}
else {
mDrawerLayout.openDrawer(leftDrawerList);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
You need to extend either ActionbarActivity, or AppCompatActivity, and use a Toolbar widget to be in the beginning of your Activity. In your activities on create, do the following:
public class YourActivity extends ActionBarActivity{
...
...
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
//Set toggle with toolbar now!
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
mToolbar,
R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
And for your Toolbar that lives in your activity xml (the very first element for your layout!)
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:background="#color/primary_color"
android:title="#string/app_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
app:theme="CreateSomeStyleHereIfYouNeed"
app:popupTheme="#android:style/Theme.Holo.Light"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
</android.support.v7.widget.Toolbar>
I fix the problem changing this function
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(mDrawerLayout.isDrawerOpen(leftDrawerList)) {
mDrawerLayout.closeDrawer(leftDrawerList);
}
else {
mDrawerLayout.openDrawer(leftDrawerList);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
New function that fix the problem
#Override public boolean onOptionsItemSelected(MenuItem item) {if (mDrawerToggle.onOptionsItemSelected(item)){ return true; } return super.onOptionsItemSelected(item); }
My program currently allows me to open the navigation bar by sliding my finger but will not display a menu button so i can click the menu button to open it. I have the onPostCreate and onOptionsItem Overide functions but I do not believe they are ever called. How do I fix this problem.
My programs minimum API level is 8 so I don't know if that is a problem.Thank you!
Main Activity:
public class Home_Page extends ActionBarActivity implements AdapterView.OnItemClickListener{
NavigationDrawer drawerLayout;
ListView listViewLeft, listViewRight;
String selectedMenuItem;
MyListViewAdapter myListViewAdapter;
int[] images = {R.drawable.menu_icon, R.drawable.menu_icon, R.drawable.menu_icon, R.drawable.menu_icon};
String[] listViewLeftItems = {"Home", "Choice 2", "Choice 3", "Choice 4"};
Intent intent;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home__page);
drawerLayout = new NavigationDrawer(this, (DrawerLayout) findViewById(R.id.drawerLayout), getSupportActionBar());
drawerLayout.createDrawer();
initializeVar();
myListViewAdapter = new MyListViewAdapter(this, images, listViewLeftItems);
listViewLeft.setAdapter(myListViewAdapter);
listViewLeft.setOnItemClickListener(this);
}
public void initializeVar(){
listViewLeft = (ListView) findViewById(R.id.drawerListLeft);
listViewRight = (ListView) findViewById(R.id.drawerListRight);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
drawerLayout.closeDrawers();
switch(position){
case 0:
selectListViewItemLeft(position);
new Thread() {
public void run() {
try {
intent = new Intent(Home_Page.this, Home_Page.class);
startActivity(intent);
finish();
}catch (Exception e){
e.printStackTrace();
}
}
}.start();
break;
case 1:
selectListViewItemLeft(position);
new Thread() {
public void run() {
try {
Intent intent = new Intent(Home_Page.this, AddAthlete.class);
startActivity(intent);
finish();
}catch (Exception e){
e.printStackTrace();
}
}
}.start();
break;
case 2:
selectListViewItemLeft(position);
break;
case 3:
selectListViewItemLeft(position);
break;
}
}
public void selectListViewItemLeft(int position){
listViewLeft.setItemChecked(position, true);
selectedMenuItem = listViewLeftItems[position];
}
}
Navigation Drawer Class: (Custom class so can create new navigation bar in different activities)
public class NavigationDrawer extends Activity{
DrawerLayout drawerLayout;
ActionBarDrawerToggle drawerToggle;
Activity currentActivity;
android.support.v7.app.ActionBar actionBar;
NavigationDrawer(Context context, DrawerLayout drawerLayout, android.support.v7.app.ActionBar actionBar) {
this.currentActivity = (Activity) context;
this.drawerLayout = drawerLayout;
this.actionBar = actionBar;
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void createDrawer() {
drawerToggle = new ActionBarDrawerToggle(currentActivity, drawerLayout, R.drawable.menu_icon, R.string.drawer_open, R.string.drawer_closed) {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
actionBar.setTitle("Menu");
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
actionBar.setTitle(getTitle());
}
};
drawerLayout.setDrawerListener(drawerToggle);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setIcon(android.R.color.transparent);
actionBar.setHomeButtonEnabled(true);
}
public void closeDrawers(){
drawerLayout.closeDrawers();
}
// Displays toggle button to expand drawer
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
Log.e("", "onPostCreate Run");
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(drawerToggle.onOptionsItemSelected(item)){
Log.e("", "onOptionsItemSelected Run");
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
Log.e("", "onConfigurationChanged Run");
}
}
In your activity's layout file, use drawer layout as your parent layout and add toolbar as child view. For ex:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/DrawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:elevation="7dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical>
<include
android:id="#+id/tool_bar"
layout="#layout/tool_bar"></include>
<!-- Add your Main Content Here -->
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="left">
<!-- Add your Drawer layout content here -->
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
And your toolbar layout, tool_bar.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="?attr/actionBarSize"
android:background="#color/action_bar_color"
app:theme="#style/ThemeOverlay.AppCompat.ActionBar"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
</android.support.v7.widget.Toolbar>
I recently started updating my app to use the new Toolbar component introduced in Android 5.0 with navigation drawer. Flow of app is : MainActivity which has a toolbar, navigation drawer with menu 1. Home 2. Cart.
Home Menu navigates to "Home Detail" through a button in it.
Layout of "MainActivity" :
<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
android:id="#+id/toolbar"
layout="#layout/toolbar" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout android:id="#+id/activity_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ListView
android:id="#+id/left_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/white"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:listSelector="#android:color/transparent" />
</android.support.v4.widget.DrawerLayout>
I am adding two fragments HomeFragment,CartFragment on "MainActivity" on menu selected from drawer as below, default selection is position 0 i.e "Home"
class "MainActivity.java" ::
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
drawer = (DrawerLayout) findViewById(R.id.drawer);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
tvTitle = (TextView) mToolbar.findViewById(R.id.toolbar_title);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
}
mDrawerToggle = new ActionBarDrawerToggle(this, drawer,mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
}
};
drawer.setDrawerListener(mDrawerToggle);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
dataList = new ArrayList<DrawerItem>();
dataList.add(new DrawerItem(Constants.V_HOME, R.drawable.ic_launcher));
dataList.add(new DrawerItem(Constants.V_MY_CART, R.drawable.ic_launcher));
mDrawerList.setAdapter(adapterDrawer);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// to show first "Home fragment" on start up of application
if(savedInstanceState==null)
SelectItem(0);
}
public void SelectItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
replaceFragment(fragment, Constants.V_TAG_HOME,false,"Home");
break;
case 1:
fragment = new CartFragment();
replaceFragment(fragment, Constants.V_TAG_MY_CART,false,"My Cart");
break;
}
drawer.closeDrawer(mDrawerList);
}
public void replaceFragment(Fragment fragment,String fragment_tag,boolean showHome,String title){
frgManager = this.getSupportFragmentManager();
FragmentTransaction ft = frgManager.beginTransaction();
ft.replace(R.id.activity_frame,fragment,fragment_tag);
if(showHome)
ft.addToBackStack(null);
ft.commit();
shouldDisplayHomeUp(showHome);
}
public void shouldDisplayHomeUp(boolean showHome){
if(showHome){
mDrawerToggle.setDrawerIndicatorEnabled(false);
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}else{
mDrawerToggle.setDrawerIndicatorEnabled(true);
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(false);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case android.R.id.home:
Toast.makeText(getApplicationContext(),"main act clicked", Toast.LENGTH_SHORT).show();
return false;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if(frgManager.getBackStackEntryCount()>0){
getSupportFragmentManager().popBackStack();
// show the drawer icon when on moving back
shouldDisplayHomeUp(false);
}else{
super.onBackPressed();
}
mDrawerToggle.syncState();
}
My home fragment has button "Detail" on click of button,replaces to other fragment :"HomeDetailFragment"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btnDetail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Home detail" />
<FrameLayout
android:id="#+id/home_frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
class "HomeFragment.java" btnDetail click event which replace to other fragment "HomeDetailFragment"::
btnDetail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Fragment fragment = new HomeDetailFragment();
((MainActivity)getActivity()).showDrawerIndicator(false);
FragmentManager frManager = getActivity().getSupportFragmentManager();
FragmentTransaction ft = frManager.beginTransaction();
ft.addToBackStack(null);
ft.replace(R.id.activity_frame, fragment).commit();
}
});
class "HomeDetailFragment.java" ::
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// update the actionbar to show the up carat/affordance
((MainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// your code for order here
Toast.makeText(getActivity(), "home detail", Toast.LENGTH_LONG).show();
((MainActivity)getActivity()).onBackPressed();
return true;
}
return true;
}
My problems ::
1. In "HomeDetailFragment", I can see the "UP home icon" but cannot get the click event of home icon onOptionsItemSelected not being called, so cant navigate back to HomeFragment
2. When pressing the Phone Back Button, and again navigating to "Home Detail" it is not showing "UP home icon"
Please guide me.
In "HomeDetailFragment", I can see the "UP home icon" but cannot get the click event of home icon onOptionsItemSelected not being called, so cant navigate back to HomeFragment
One way to achieve this is by using the Toolbar from your MainActivity like so:
Toolbar mToolbar= ((MainActivity)getActivity()).mToolbar;
mToolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_nav_back));
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("MrE", "home selected");
}
});
When pressing the Phone Back Button, and again navigating to "Home Detail" it is not showing "UP home icon"
The reason your code isn't getting called is because it is in the onCreate of your Fragment. Move it to the onCreateOptionsMenu instead to have it update.
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Put toolbar stuff from above here
super.onCreateOptionsMenu(menu, inflater);
}
I had the exact issue.
Use the setToolbarNavigationClickListener method.
In MainActivity.java,
actionBarToggle.setToolbarNavigationClickListener(new View.OnClickListener({
#Override
public void onClick(View v) {
MainActivity.this.onSupportNavigateUp();
}
});
Avoid implementing Up Navigation individually in Fragments.
You called getSupportActionBar().setDisplayHomeAsUpEnabled(true) which shows the button in the toolbar but doesn't activate it.
Calling getSupportActionBar().setHomeButtonEnabled(true); in addition should do the job.
You show the back-button in the toolbar from within the Fragment which is something I would avoid. Try moving this part to your Activity, when you do the FragmentTransaction.