I have a simple android.support.v7.widget.Toolbar and all I am trying to do is to open a NavigationDrawer by pressing the "hamburger" icon in the top left corner. The "hamburger" button is visible, and when I start to pull from the left I see the animation on the button but pressing the button does not open/close the NavigationDrawer as I expect. I have followed the [Google Documentation][1] and still am not able to figure this out. Sorry for any confusion, below is the simplified code I am currently attempting to use:
public class MainActivity extends AppCompatActivity implements
View.OnClickListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("NICK", "button button button..................");
}
});
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
NavigationView n = (NavigationView) findViewById(R.id.nav);
mDrawerLayout.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Log.d("NICK", "button button button..................");
}
});
//mDrawerLayout.setDrawerListener(mDrawerToggle);
n.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
////.......
}
mDrawerLayout.closeDrawers(); // CLOSE DRAWER
return true;
}
});
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d("NICK","CWECNEWKVNERIPNVIEWNFVIPEWNVIPEWNVPIEWNVPIEWNVPIEWNVPIRWNVPRWVPO");
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START); // OPEN DRAWER
Log.d("NICK","CWECNEWKVNERIPNVIEWNFVIPEWNVIPEWNVPIEWNVPIEWNVPIEWNVPIRWNVPRWVPO");
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.drawer, menu);
return true;
}
}
}
And as it is I do not get any of the log debug statements when running.
This is essentially the issue I have: https://stackoverflow.com/a/26636045/1489990. I've followed this and it just doesn't work.
It is my understanding that setNavigationOnClickListener is called when the hamburger icon is pressed, and this is where I am focusing my efforts is to get the event handled properly because when I press the button I do not get my log statement. Let me know if this idea is incorrect. https://developer.android.com/reference/android/widget/Toolbar.html#setNavigationOnClickListener(android.view.View.OnClickListener)
My Layouts:
ActivityMain.xml
<RelativeLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/d"
android:background="#drawable/home_wall">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:layout_marginBottom="10dp"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:layout_marginTop="25dp"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" />
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:id="#+id/drawer"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<ImageView
android:layout_width="fill_parent"
android:layout_height="200dp"
android:id="#+id/imageView"
android:src="#drawable/trans2"
android:layout_alignParentTop="true"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:paddingBottom="300dp" />
<RelativeLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/d8"
android:layout_alignParentTop="true"
android:layout_alignLeft="#+id/imageView"
android:layout_alignStart="#+id/imageView"
android:paddingTop="0dp">
<Button
android:layout_width="75dp"
android:layout_height="50dp"
android:text="Gallery"
android:id="#+id/save_button"
android:background="#dd2c00" android:textColor="#fff"
android:layout_below="#+id/Purchases"
android:layout_toRightOf="#+id/start_button"
android:layout_toEndOf="#+id/start_button" />
<Button
android:layout_width="125dp"
android:layout_height="50dp"
android:text="Store"
android:id="#+id/Purchases"
android:background="#ff6e40" android:textColor="#fff"
android:layout_above="#+id/instructions_button6"
android:layout_toLeftOf="#+id/start_button"
android:layout_toStartOf="#+id/start_button"
android:layout_marginBottom="98dp" />
<Button
android:layout_width="75dp"
android:layout_height="50dp"
android:text="Help"
android:id="#+id/instructions_button6"
android:background="#dd2c00" android:textColor="#fff"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="#+id/start_button"
android:layout_toStartOf="#+id/start_button"
android:layout_marginLeft="5dp"
android:layout_marginBottom="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="300dp"
android:text="Start"
android:id="#+id/start_button"
android:background="#ff3d00"
android:textColor="#fff"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp" />
<Button
android:layout_width="125dp"
android:layout_height="50dp"
android:text="Achievements"
android:id="#+id/Scores"
android:background="#ff6e40" android:textColor="#fff"
android:layout_alignTop="#+id/Purchases"
android:layout_toRightOf="#+id/start_button"
android:layout_toEndOf="#+id/start_button" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to the quiz!"
android:id="#+id/textView"
android:textColor="#fff"
android:textSize="20dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp" />
<!-- sign-in button -->
<com.google.android.gms.common.SignInButton
android:id="#+id/sign_in_button"
android:layout_width="110dp"
android:layout_height="50dp"
android:layout_above="#+id/start_button"
android:layout_centerHorizontal="true"
android:visibility="visible" />
<!-- sign-out button -->
<Button
android:id="#+id/sign_out_button"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:text="Sign Out"
android:visibility="invisible"
android:background="#dd4b39"
android:textColor="#fff"
android:layout_alignTop="#+id/sign_in_button"
android:layout_centerHorizontal="true"
android:layout_marginTop="160dp" />
</RelativeLayout>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#fff"
android:id="#+id/nav"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/drawer"/>
</android.support.v4.widget.DrawerLayout>
Drawer.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_menu"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:title="Google Play Games"
android:icon="#drawable/ic_local_airport_white_48dp">
<menu>
<item
android:id="#+id/Sign_in_drawer"
android:icon="#drawable/games_controller_grey"
android:title="Sign in" />
<item
android:id="#+id/ach"
android:icon="#drawable/games_achievements"
android:title="Achievements" />
</menu>
</item>
<item android:title="Start a Quiz"
android:icon="#drawable/ic_local_airport_white_48dp">
<menu>
<item
android:id="#+id/quizStart25"
android:icon="#drawable/ic_local_airport_white_48dp"
android:title="25 Questions" />
<item
android:id="#+id/quizStart10"
android:icon="#drawable/ic_local_airport_white_48dp"
android:title="10 Questions" />
</menu>
</item>
<group
android:checkableBehavior="single">
<item
android:id="#+id/gallery"
android:icon="#drawable/ic_photo_library_white_48dp"
android:title="Gallery" />
<item
android:id="#+id/stats"
android:icon="#drawable/ic_toc_white_48dp"
android:title="Statistics" />
<item
android:id="#+id/store"
android:icon="#drawable/ic_shop_white_48dp"
android:title="Store" />
<item
android:id="#+id/settings"
android:icon="#drawable/ic_settings_white_48dp"
android:title="Settings" />
<item
android:id="#+id/about"
android:icon="#drawable/ic_info_white_48dp"
android:title="About" />
</group>
<item android:title="Support">
<menu>
<item
android:id="#+id/help_drawer"
android:icon="#drawable/ic_help_white_48dp"
android:title="Help" />
<item
android:id="#+id/report"
android:icon="#drawable/ic_report_problem_white_48dp"
android:title="Contact Developer" />
<item
android:id="#+id/GPlusCommunity"
android:icon="#drawable/btn_g_white_normal"
android:title="Google+ Community" />
</menu>
</item>
In your ActivityMain.xml, the toolbar is outside of the DrawerLayout. That's the problem. If you want Toolbar to interact with DrawLayout, Toolbar needs to be a child of DrawerLayout.
To fix the problem, make DrawerLayout the root of your activity. Here's the documentation. The relevant quote is:
To add a navigation drawer, declare your user interface with a
DrawerLayout object as the root view of your layout. Inside the
DrawerLayout, add one view that contains the main content for the
screen (your primary layout when the drawer is hidden) and another
view that contains the contents of the navigation drawer.
So basically, structure your ActivityMain.xml to be something like this:
<android.support.v4.widget.DrawerLayout ...>
<RelativeLayout ...>
<android.support.v7.widget.Toolbar .../>
<!-- Your other content goes here -->
</RelativeLayout>
<android.support.design.widget.NavigationView .../>
</android.support.v4.widget.DrawerLayout>
That should take care of the problem.
Override onOptionsItemSelected method and use below
if(item.getItemId() == android.R.id.home){ // use android.R.id
mDrawerLayout.openDrawer(Gravity.LEFT);
}
You need to sync the drawer toggle:
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
EDIT: That code is working for me (copied from your post)
public class TempActivity extends AppCompatActivity {
private ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.temp);
setupDrawer();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(final MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
private void setupDrawer() {
Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.my_drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,toolbar,R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
}
<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/my_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<RelativeLayout
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:text="DRAMER MENU" />
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
But if you are using the new NavigationView, then you don't need the toggle etc. Here is a good example how to use it.
I fixed it by giving openable which is drawerLayout to navigateUp function.
More info navigateUp Doc
override fun onSupportNavigateUp(): Boolean {
val navController = this.findNavController(R.id.host_fragment)
return NavigationUI.navigateUp(navController,drawer_layout)
}
If it helps somebody, to me it happened the same because of the stupid error of calling setSupportActionBar(toolbar) two times. Just call it once in onCreate method and never again. My mistake was I called it later in another method.
Use ActionBarDrawerToggle and implement public boolean onOptionsItemSelected(MenuItem item)
Toolbar DOES NOT have to be within a DrawerLayout, it's not likely to be the cause of this issue. toggle.onOptionsItemSelected(item) looks for the ID of the item selected and if it is android.R.id.home then the drawer's visibility is toggled. Thus Toolbar, or any View that creates a Home MenuItem, can be placed anywhere in your layout.
Within your activity:
ActionBarDrawerToggle toggle;
private void setupDrawerToggleInActionBar() {
// assuming a Toolbar has been initialized in your onCreate
this.setSupportActionBar(toolbar);
// setup the action bar properties that give us a hamburger menu
ActionBar actionBar = this.getSupportActionBar();
if(actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
// the toggle allows for the simplest of open/close handling
toggle = new ActionBarDrawerToggle(this,
drawerLayout,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
// drawerListener must be set before syncState is called
drawerLayout.setDrawerListener(toggle);
toggle.setDrawerIndicatorEnabled(true);
toggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// This is required to make the drawer toggle work
if(toggle.onOptionsItemSelected(item)) {
return true;
}
/*
* if you have other menu items in your activity/toolbar
* handle them here and return true
*/
return super.onOptionsItemSelected(item);
}
Simply call function onOptionsItemSelected(MenuItem menuItem) of ActionBarDrawerToggle class on activity options menu managing function like below.
mDrawerToggle= new ActionBarDrawerToggle(activity, drawerLayout, R.string.nav_drawer_accessbility_drawer_open,
R.string.nav_drawer_accessbility_drawer_close);
#Override
public boolean onOptionsItemSelected(final android.view.MenuItem item) {
navigation().getOptionsMenuInflater(this).closeSearchView();
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this behavior.
mDrawerToggle.onOptionsItemSelected(item);
return super.onOptionsItemSelected(item);
}
OR
override onOptionsItemSelected of activity like below
public boolean onOptionsItemSelected(MenuItem item) {
if (item != null && item.getItemId() == android.R.id.home) {
toggle();
}
return super.onOptionsItemSelected(item);
}
private void toggle() {
if (mDrawerLayout.isDrawerVisible(GravityCompat.START)) {
mDrawerLayout.closeDrawer(GravityCompat.START);
} else {
mDrawerLayout.openDrawer(GravityCompat.START);
}
}
For the drawer toggle you need to set "display home as up" to false:
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
As i have no specific answer to your problem, i want to suggest a completely different approach:
In my projects im using the Material Drawer developed by Mike Penz.
Its looks really nice, is easy to implement, and there is not much you have to worry about.
So if you cant find a solution for your problem, you could give it a try.
While accepted answer here works alright however, as they say "Prevention is better than cure".. Adding mDrawerToggle.syncState(); in onPostCreate and onConfigurationChanged() wroks much better as answerd by #mbmc above:
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
After a lot of different problems I found a way to make it work putting Toolbar Widget inside AppBarLayout.
Be sure that there is no other layout on top of widget toolbar!
<androidx.drawerlayout.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/drawable_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
xmlns:android="http://schemas.android.com/apk/res/android">**
<androidx.appcompat.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_page_toolbar"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:background="#color/colorPrimaryDark"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>**
.... YOUR LAYOUT ...
</RelativeLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:layout_marginBottom="3dp"
app:menu="#menu/navigation_menu">
</com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
Idk why...but changing return value to false rather than true fixed the ham Icon for me. on onOptionItemSelected override method
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if(item.getItemId() == R.id.logout){
ParseUser.logOut();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
Toast.makeText(this, "Logout Successful!", Toast.LENGTH_SHORT).show();
} else if(item.getItemId() == R.id.action_settings){
Toast.makeText(this, "No setting to update! Will be available later...", Toast.LENGTH_SHORT).show();
}
return true; // here change this to false
}
If none of the above answer works, please cross check again,
First you need to call setSupportActionBar(toolbar); and then do the necessary work for nav drawer. I wasted my 2 hours because of this silly mistake.
I had the same problem. However, it did not occur on all fragments. It occurred on one particular fragment.
Firstly, please follow #hungryghost 's answer mentioned above. Then do the following.
Adding the following piece of code helped the drawer open on click of the hamburger icon. It worked flawlessly for me. Thank you very much. :) My sincere apologies if this isn't the right way.
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int itemId = item.getItemId();
if(itemId == android.R.id.home){
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
I have found a simple solution to this problem is to call the setSupportActionBar(toolbar) method before the navigation drawer functions.
Related
I have watched a lot of solutions but I'm in trouble with my NavigationView. I created it and tried to use it but somehow it doesn't react. This is the code I used.
Thank you !
This is my XML for "drawermenu"
<?xml version="1.0" encoding="utf-8"?>
<item
android:id="#+id/add"
android:icon="#drawable/ic_add_circle_black_24px"
android:title="Добави автомобил" />
<item
android:id="#+id/settings"
android:icon="#drawable/ic_build_black_24px"
android:title="Настройки" />
<item
android:id="#+id/export"
android:icon="#drawable/ic_importexport"
android:title="Експорт на инф."
/>
<item
android:id="#+id/about"
android:icon="#drawable/ic_info_outline_black_24px"
android:title="За програмиста" />
<item
android:id="#+id/exit"
android:icon="#drawable/ic_exit_to_app_black_24px"
android:iconTintMode="src_in"
android:title="Изход" />
</group>
This is all I used for NavigationView
<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/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#color/myYellow"
android:paddingRight="10dp"
android:theme="#style/AppTheme2"
tools:context="com.example.hpdemon.diploma.MainForm"
tools:openDrawer="start">
<FrameLayout
android:id="#+id/flcontent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nv"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/myYellow"
android:fitsSystemWindows="true"
app:headerLayout="#layout/header"
app:itemIconTint="#color/colorPrimaryDark"
app:itemTextColor="#56733b"
app:menu="#menu/drawermenu">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
And this is the code from MainActivity. I call the Drawer function in onCreate method
public void Drawer() {
NavigationView navigationView = findViewById(R.id.nv);
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
// close drawer when item is tapped
int id = menuItem.getItemId();
if (id == R.id.add) {
//Handle your stuff here
Toast.makeText(MainForm.this, "Ще проработя ;) ", Toast.LENGTH_LONG).show();
}
mDrawerLayout.closeDrawers();
// Add code here to update the UI based on the item selected
// For example, swap UI fragments here
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
This is for the mToggle element
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
Can anyone please help me on designing this android layout? I want to put two icons on the drawer toolbar like on the image below.
This is LeftNavigationActivity.class
public class LeftNavigationActivity extends BaseActivity
implements NavigationView.OnNavigationItemSelectedListener {
private ImageView profilePic;
Session session;
FragmentManager fragmentManager = getSupportFragmentManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_left_navigation);
this.setTitle("Home");
session = new Session(this);
if (!session.loggedIn()) {
logOut();
}
View v = getLayoutInflater().inflate(R.layout.nav_header_left_navigation,
null);
TextView username = (TextView) v.findViewById(R.id.username);
Intent intent = getIntent();
String uname = intent.getStringExtra("username");
Toast.makeText(this, "Welcome " + uname, Toast.LENGTH_SHORT).show();
username.setText(uname);
LoansAndDebtsFragment loansAndDebtsFragment = new LoansAndDebtsFragment();
fragmentManager.beginTransaction().replace(R.id.layout_for_fragment,
loansAndDebtsFragment, loansAndDebtsFragment.getTag()).commit();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(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();
NavigationView navigationView = (NavigationView)
findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
FragmentManager fragmentManager = this.getSupportFragmentManager();
int stackCount = fragmentManager.getBackStackEntryCount();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (fragmentManager.getFragments() != null) {
LoansAndDebtsFragment loansAndDebtsFragment = new
LoansAndDebtsFragment();
fragmentManager.beginTransaction().replace(R.id.layout_for_fragment,
loansAndDebtsFragment, loansAndDebtsFragment.getTag()).commit();
}
}
The LeftNavigationActivity is the BaseDrawerActivity which contains the navigation menu.
This is app_bar_left_navigation.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"
tools:context="com.gebeya.jo.pyf.activities.LeftNavigationActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.NoToolBarWithABrandTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorWhite"
app:titleTextColor="#color/colorBrand1"
app:popupTheme="#style/AppTheme.NoToolBarWithABrandTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_left_navigation" />
</android.support.design.widget.CoordinatorLayout>
This is nav_header_left_navigation.xml
<?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="190dp"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#drawable/nav_background"
android:orientation="vertical">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/profile_image"
android:layout_width="80dp"
android:layout_height="80dp"
android:src="#drawable/eyasu"
android:layout_marginLeft="20dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
app:civ_border_color="#color/colorBrand1"
app:civ_border_width="4dp"
android:layout_alignParentStart="true"
android:paddingBottom="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/userFullName"
android:textSize="14sp"
android:textColor="#FFF"
android:textStyle="bold"
android:gravity="left"
android:paddingBottom="4dp"
android:id="#+id/username"
android:layout_above="#+id/email"
android:layout_alignLeft="#+id/profile_image"
android:layout_alignStart="#+id/profile_image" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/email"
android:hint="#string/userEmail"
android:gravity="left"
android:layout_marginBottom="8dp"
android:textSize="14sp"
android:textColor="#fff"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/username"
android:layout_alignStart="#+id/username" />
</RelativeLayout>
Open Android Studio
Start a new Android Studio project
Select Navigation Drawer Activity
Pick your icons here: https://material.io/icons/
1. Create an menu XML with your desired menu items and put this XML into res/menu/ folder.
menu.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="com.ferdous.advancefilter.MainActivity">
<item
android:id="#+id/action_notification"
android:title="Notification"
android:icon="#drawable/ic_action_notification"
app:showAsAction="always" />
<item
android:id="#+id/action_warning"
android:title="Notification"
android:icon="#drawable/ic_action_warning"
app:showAsAction="always" />
</menu>
2. In your Activity, override method onCreateOptionsMenu() to add menu items to Toolbar and override method onOptionsItemSelected() to handle the Toolbar item click event.
#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();
switch (id) {
case R.id.action_notification:
// Do something
break;
case R.id.action_warning:
// Do something
break;
}
return super.onOptionsItemSelected(item);
}
OUTPUT:
#. If you want to add count badge over your menu item like below then you can follow my another answer Notification Badge On Action Item Android. I have added detail steps and codes.
Hope this will help~
I had a PreferenceActivity which was working fine. Then, I decided to add a navigation drawer to it, and edited the layouts according to my other activity layouts which also have working navigation drawers. However, after doing that, my PreferenceActivity stopped opening and started throwing a NPE on start. I can't even open that activity anymore. Problem is in onCreate, obviously, and also in an onClick method as stated in the logcat. Yet, there are two onClick's in this activities onCreate, and I'm not seeing how those result in a NPE, since they are the exact same in my other working activities. My layout xmls are seperated into 3 xmls according to the default DrawerLayout implementation. Without further due, here are the codes and xmls:
PreferenceActivity:
public class FirstYearCoursesActivity extends PreferenceActivity
implements NavigationView.OnNavigationItemSelectedListener {
private AppCompatDelegate mDelegate;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first_year_courses);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar((toolbar));
Window window = this.getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(this.getResources().getColor(R.color.colorPrimaryDark));
addPreferencesFromResource(R.xml.prefs);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view2);
navigationView.setNavigationItemSelectedListener(this);
View headerView = navigationView.getHeaderView(0);
ImageButton logoutButton = (ImageButton) headerView.findViewById(R.id.logoutButton);
logoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(FirstYearCoursesActivity.this, LoginActivity.class);
startActivity(intent);
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
protected void onPause() {
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final Handler handler = new Handler();
if (drawer.isDrawerOpen(GravityCompat.START)) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
drawer.closeDrawer(GravityCompat.START);
}
}, 200);
super.onPause();
} else {
super.onPause();
}
}
private void setSupportActionBar(#Nullable Toolbar toolbar) {
getDelegate().setSupportActionBar(toolbar);
}
private AppCompatDelegate getDelegate() {
if (mDelegate == null) {
mDelegate = AppCompatDelegate.create(this, null);
}
return mDelegate;
}
#Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
String key = preference.getKey();
switch (key) {
case "math119":
Intent intent = new Intent(FirstYearCoursesActivity.this, Math119Activity.class);
startActivity(intent);
break;
default:
Toast.makeText(this, "Other Click", Toast.LENGTH_SHORT).show();
break;
}
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// to be filled
int id = item.getItemId();
if (id == R.id.nav_camera) {
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
return true;
}
}
activity.xml:
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
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"
android:fitsSystemWindows="true">
<include
layout="#layout/app_bar_first_year_courses"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view2"
android:layout_width="250dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer"
android:background="#ffffffff"
app:itemTextColor="#000000"
app:itemTextAppearance="#style/TextAppearance.AppCompat.Body1"/>
</android.support.v4.widget.DrawerLayout>
app_bar.xml:
<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=".activities.FirstYearCoursesActivity">
<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"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"/>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_first_year_courses"/>
</android.support.design.widget.CoordinatorLayout>
content.xml:
<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:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".activities.FirstYearCoursesActivity"
tools:showIn="#layout/app_bar_first_year_courses"
android:orientation="vertical">
</LinearLayout>
nav_header.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="140dp"
android:background="#drawable/profilebanner"
android:gravity="bottom"
android:orientation="vertical"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
android:id="#+id/header">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/logoutButton"
android:src="#drawable/ic_power_settings_new_white_18dp"
android:background="#00ffffff"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="30dp"
android:layout_marginRight="10dp"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/headerClick"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp"
android:paddingTop="20dp">
<ImageView
android:layout_width="65dp"
android:layout_height="65dp"
android:id="#+id/imageView"
android:background="#drawable/onur"
android:layout_centerVertical="true"
android:layout_alignParentStart="false"
android:layout_alignBottom="#+id/textView3"
android:layout_marginBottom="-20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Onur Çevik"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:id="#+id/textView2"
android:textSize="13sp"
android:layout_toRightOf="#+id/imageView"
android:layout_marginLeft="25dp"
android:layout_marginTop="45dp"/>
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Environmental Engineering"
android:textSize="11sp"
android:layout_toRightOf="#+id/imageView"
android:layout_marginLeft="25dp"
android:layout_below="#+id/textView2"
android:layout_alignParentStart="false"/>
</RelativeLayout>
</RelativeLayout>
prefs.xml:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:key="firstyearprefs">
<Preference
android:title="Math-119"
android:key="math119"/>
<Preference
android:title="Math-120"
android:key="math120"/>
<Preference
android:title="Phys-105"
android:key="phys105"/>
<Preference
android:title="Phys-106"
android:key="phys106"/>
<Preference
android:title="Chem-107"
android:key="chem107"/>
<Preference
android:title="Eng-101"
android:key="eng101"/>
<Preference
android:title="Eng-102"
android:key="eng102"/>
<Preference
android:title="Ce-101"
android:key="ce101"/>
</PreferenceScreen>
logcat:
02-08 02:10:35.415 30815-30815/com.theoc.proto E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.theoc.proto, PID: 30815
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
at android.preference.PreferenceScreen.bind(PreferenceScreen.java:143)
at android.preference.PreferenceActivity.bindPreferences(PreferenceActivity.java:1419)
at android.preference.PreferenceActivity.access$000(PreferenceActivity.java:123)
at android.preference.PreferenceActivity$1.handleMessage(PreferenceActivity.java:230)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
EDIT:
One thing worth mentioning is that I triple checked the activity and it's adapter that leads to this PreferenceActivity on list item click. I reversed all my Drawer Layout implementations, and I was able to open this PreferenceActivity through parent activity. Navigation Drawer code, or layouts are the ones messing with it. I'm getting the listview.onclick(adapter) NPE because my list item click on parent activity goes to a null reference, which in this case it the PreferenceActivity itself. Also debug didn't show me anything null in PreferenceActivity's onCreate, except savedInstanceState.
I was able to reproduce the same NPE using your code and fixed it by replacing the addPreferencesFromResource call (note that it's deprecated) using a fragment instead as described in these threads:
Android: Preference Fragment with a Navigation Drawer's Fragment
What to use instead of "addPreferencesFromResource" in a PreferenceActivity?
Although, on my version, the preferences view overlaps the toolbar and I am not sure what the activity layout should be to fix that, maybe it will be OK in yours.
I have followed some examples online to implement a Navigation Drawer + Action Bar + Translucent Status Bar. The translucent status bar does not turn into transparent at all.
Here's my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:label="#string/app_name"
android:theme="#style/AppBaseTheme"
android:icon="#mipmap/ic_launcher">
<activity
android:name="com.getbase.floatingactionbutton.sample.MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
v21/styles.xml
<style name="AppBaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowActionBar">false</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:windowTranslucentStatus">true</item>
<item name="android:statusBarColor">#android:color/transparent</item>
<item name="android:colorPrimary">#color/ColorPrimary</item>
<item name="android:colorPrimaryDark">#color/ColorPrimaryDark</item>
<!-- Customize your theme here. -->
</style>
<style name="menu_labels_style">
<item name="android:background">#drawable/fab_label_background</item>
<item name="android:textColor">#color/simplify_blue</item>
<item name="android:textStyle">bold</item>
</style>
activity_main.xml
<!-- Beginning of Navigation Drawer -->
<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:id="#+id/DrawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<!-- Beginning of Floating Action Menu -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fab="http://schemas.android.com/apk/res-auto"
android:background="#color/background"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/tool_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="#color/ColorPrimary"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent">
<com.getbase.floatingactionbutton.FloatingActionsMenu
android:id="#+id/simplify_actions"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
fab:fab_addButtonColorNormal="#color/simplify_blue"
fab:fab_addButtonColorPressed="#color/simplify_blue_pressed"
fab:fab_addButtonPlusIconColor="#color/white"
fab:fab_labelStyle="#style/menu_labels_style"
android:layout_marginBottom="16dp"
android:layout_marginRight="16dp"
android:layout_marginEnd="16dp">
<com.getbase.floatingactionbutton.FloatingActionButton
android:id="#+id/action_scan_qr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
fab:fab_colorNormal="#color/white"
fab:fab_title="SCAN QR CODE"
fab:fab_size="mini"
fab:fab_icon="#drawable/ic_scan_qr_code"
fab:fab_colorPressed="#color/white_pressed"/>
<com.getbase.floatingactionbutton.FloatingActionButton
android:id="#+id/action_share_hotspot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
fab:fab_colorNormal="#color/white"
fab:fab_title="SHARE HOTSPOT"
fab:fab_size="mini"
fab:fab_icon="#drawable/ic_share_wifi"
fab:fab_colorPressed="#color/white_pressed"/>
<com.getbase.floatingactionbutton.FloatingActionButton
android:id="#+id/action_discovery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
fab:fab_colorNormal="#color/white"
fab:fab_title="SEARCH NETWORK"
fab:fab_size="mini"
fab:fab_icon="#drawable/ic_discover_network"
fab:fab_colorPressed="#color/white_pressed"/>
</com.getbase.floatingactionbutton.FloatingActionsMenu>
<!-- End of Floating Action Menu -->
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="304dp"
android:layout_height="match_parent"
android:layout_gravity="left|start"
android:fitsSystemWindows="true">
<android.support.v7.widget.RecyclerView
android:id="#+id/RecyclerView"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:background="#ffffff"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
<!-- End of Navigation Drawer -->
and the MainActivity.java
public class MainActivity extends AppCompatActivity {
private boolean IS_HOTSPOT_ON = false;
String TITLES[] = {"Profile","Payment","History","Promotions","Usage","Speed","Settings"};
int ICONS[] = {R.drawable.ic_profile,R.drawable.ic_payment,R.drawable.ic_history,R.drawable.ic_promotion,R.drawable.ic_usage,R.drawable.ic_speed,R.drawable.ic_settings};
String NAME = "Yoona Im";
String EMAIL = "yoona#nextwave.my";
int PROFILE = R.drawable.yoona;
private Toolbar toolbar;
RecyclerView mRecyclerView; // Declaring RecyclerView
RecyclerView.Adapter mAdapter; // Declaring Adapter For Recycler View
RecyclerView.LayoutManager mLayoutManager; // Declaring Layout Manager as a linear layout manager
DrawerLayout Drawer; // Declaring DrawerLayout
ActionBarDrawerToggle mDrawerToggle; // Declaring Action Bar Drawer Toggle
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle(R.string.app_name);
mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView); // Assigning the RecyclerView Object to the xml View
mRecyclerView.setHasFixedSize(true); // Letting the system know that the list objects are of fixed size
mAdapter = new MyAdapter(TITLES,ICONS,NAME,EMAIL,PROFILE); // Creating the Adapter of MyAdapter class(which we are going to see in a bit)
// And passing the titles,icons,header view name, header view email,
// and header view profile picture
mRecyclerView.setAdapter(mAdapter); // Setting the adapter to RecyclerView
mLayoutManager = new LinearLayoutManager(this); // Creating a layout Manager
mRecyclerView.setLayoutManager(mLayoutManager); // Setting the layout Manager
Drawer = (DrawerLayout) findViewById(R.id.DrawerLayout); // Drawer object Assigned to the view
mDrawerToggle = new ActionBarDrawerToggle(this,Drawer,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_close){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
// code here will execute once the drawer is opened( As I dont want anything happened whe drawer is
// open I am not going to put anything here)
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
// Code here will execute once drawer is closed
}
}; // Drawer Toggle Object Made
final FloatingActionsMenu menuSimplifyActions = (FloatingActionsMenu) findViewById(R.id.simplify_actions);
final FloatingActionButton actionScanQR = (FloatingActionButton) findViewById(R.id.action_scan_qr);
actionScanQR.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
actionScanQR.setTitle("SCANNING CODE NOW...");
}
});
final FloatingActionButton actionShareHotspot = (FloatingActionButton) findViewById(R.id.action_share_hotspot);
actionShareHotspot.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (!IS_HOTSPOT_ON) {
actionShareHotspot.setIcon(R.drawable.ic_disable_hotspot);
actionShareHotspot.setTitle("SWITCH OFF HOTSPOT");
}
else {
actionShareHotspot.setIcon(R.drawable.ic_share_wifi);
actionShareHotspot.setTitle("SHARE HOTSPOT");
}
IS_HOTSPOT_ON = !IS_HOTSPOT_ON;
}
});
Drawer.setDrawerListener(mDrawerToggle); // Drawer Listener set to the Drawer toggle
mDrawerToggle.syncState(); // Finally we set the drawer toggle sync State
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#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;
}
return super.onOptionsItemSelected(item);
}
}
Change this
<item name="android:colorPrimaryDark">#color/ColorPrimaryDark</item>
to
<item name="android:colorPrimaryDark">#android:color/transparent</item>
this will transparent your status bar.
I added navigation drawer to my application. Everything works fine, but now I am trying to add a simple textView to menu, and am not succeeding. The problem is the fact that text is hidden underneath actionBar itself. Even 50dp margin from top isn't enough.
Do you have any tips on how to fix this issue?
My main activity:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/container"
android:fitsSystemWindows="true"
android:clipToPadding="false"/>
<!-- The navigation drawer -->
<FrameLayout
android:id="#+id/left_drawer"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#color/dark_brown">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:textSize="40dp"
android:textColor="#ffffff"
android:id="#+id/textView"
android:layout_marginTop="50dp"
android:layout_marginLeft="20dp"
android:gravity="center_vertical"/>
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
And my main activities class:
public class MainActivity extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private DatabaseHandler database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Handle application side menu
sideMenu();
// Set tint for android bar (only for KitKat version)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
SystemBarTintManager tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarTintResource(R.color.action_bar_bg);
}
// Create system objects
database = new DatabaseHandler(this);
final Statistics statistic = new Statistics(database);
// Create main fragment and point app to it
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new MainFragment(database, statistic))
.commit();
}
}
private void sideMenu() {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this, // host Activity
mDrawerLayout, // DrawerLayout object
R.drawable.ic_drawer, // nav drawer icon to replace 'Up' caret
R.string.drawer_open, // "open drawer" description
R.string.drawer_close // "close drawer" description
) {
// Called when a drawer has settled in a completely closed state.
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(R.string.drawer_close);
}
// Called when a drawer has settled in a completely open state.
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(R.string.drawer_open);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
super.onDestroy();
database.closeDatabase();
}
}
You want to assign fitsSystemWindows and clipToPadding to the Navigation Drawer fragment (most probably the ListView)
Something like this -
<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="#cccc"
android:fitsSystemWindows="true"
android:clipToPadding="false"
/>
But in your case, you are using the FrameLayout on the activity_main itself to populate the Drawer contents. So you have to apply these two properties to the FrameLayout
<FrameLayout
android:id="#+id/left_drawer"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:fitsSystemWindows="true"
android:clipToPadding="false"
android:background="#color/dark_brown">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:textSize="40dp"
android:textColor="#ffffff"
android:id="#+id/textView"
android:gravity="center_vertical"/>
</FrameLayout>
Also, notice, you don't need following to your TextView anymore.
android:layout_marginTop="50dp"
android:layout_marginLeft="20dp"