How to make a Persistent Navigation Drawer in Android? - java

I have search a lot but manage the Navigation easily but at this time need to Implement Persistent Navigation Drawer.
https://www.google.com/design/spec/patterns/navigation-drawer.html#navigation-drawer-behavior
Please let me know the process to Manage or Sample Tutorial of **Persistent Navigation Drawer** shown in below Image. LinkedIn Android Application is using the same navigation drawer.
Thanks

I have implement "Persistent Navigation Drawer" via ViewPager and works fine as what I need.
Just use width as 0.8f in PagerAdaper/FragmentPagerAdapter
#Override
public float getPageWidth(int position) {
// TODO Auto-generated method stub
if (position == 0) {
return .8f;
}
return 1f;
}

My XML file:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:facebook="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" >
<!-- Framelayout to display Fragments -->
<RelativeLayout
android:id="#+id/mainView"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</RelativeLayout>
<!-- Listview to display slider menu -->
<RelativeLayout
android:id="#+id/drawerView"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:layout_gravity="start" >
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/list_background"
android:divider="#color/list_divider"
android:dividerHeight="1dp" />
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
My activity:
public class ProfileActivity extends ActionBarActivity {
....
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
RelativeLayout drawerView;
RelativeLayout mainView;
....
#Override
protected void onCreate(Bundle savedInstanceState) {
............. //
.............//
drawerView = (RelativeLayout) findViewById(R.id.drawerView);
mainView = (RelativeLayout) findViewById(R.id.mainView);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.app_name, R.string.app_name) {
public void onDrawerClosed(View view) {
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
supportInvalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
mainView.setTranslationX(slideOffset * drawerView.getWidth());
mDrawerLayout.bringChildToFront(drawerView);
mDrawerLayout.requestLayout();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);}
}
The code inside onDrawerSlide will get you what you want.

Related

How can i setup a base drawer for all activities

I have read a lot of answers here but could not manage to do it. I want all of my activities to have a drawer. Inside the drawer i have a ListView which contains all of the activities that the drawer should open. This is the implementation of the drawer:
public abstract class DrawerActivity extends BaseActivity {
private DrawerLayout drawerLayout;
private ListView drawerList;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.base_drawer_layout);
drawerLayout = findViewById(R.id.drawer_layout);
drawerList = findViewById(R.id.left_drawer);
final ArrayList<String> elements = new ArrayList<>();
elements.add("My tasks");
elements.add("Issues");
drawerList.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, elements));
drawerList.setOnItemClickListener(createOnDrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
drawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
drawerLayout, /* DrawerLayout object */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view)
{
getSupportActionBar().setTitle("TITLE");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView)
{
getSupportActionBar().setTitle("Title");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
drawerLayout.addDrawerListener(drawerToggle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (drawerToggle.onOptionsItemSelected(item))
return true;
return super.onOptionsItemSelected(item);
}
protected abstract DrawerItemClickListener createOnDrawerItemClickListener();
protected ListView drawerList()
{
return drawerList;
}
protected DrawerLayout drawerLayout()
{
return drawerLayout;
}
}
This is the drawer layout xml file
<?xml version="1.0" encoding="utf-8"?>
<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 -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView
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="#274"/>
</android.support.v4.widget.DrawerLayout>
Lets say i have currently two activities, My Tasks and Issues and both of them extend DrawerActivity. If i am in the Issues activity, how can i open the My Tasks activity through that drawer?
All activities that extend DrawerActivity implements createOnDrawerItemClickListener() which inside creates a new fragment with the layout of the the activity that implements DrawerActivity, which i'm pretty sure is wrong.
Example implementation:
#Override
protected DrawerItemClickListener createOnDrawerItemClickListener()
{
return new DrawerItemClickListener(position ->
{
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, new TaskFragment()).commit();
drawerList().setItemChecked(position, true);
drawerLayout().closeDrawer(drawerList());
});
}
And the DrawerItemClickListener:
public class DrawerItemClickListener implements ListView.OnItemClickListener {
private FragmentStrategy fragmentStrategy;
public DrawerItemClickListener(final FragmentStrategy fragmentStrategy)
{
this.fragmentStrategy = fragmentStrategy;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
fragmentStrategy.showFragment(position);
}
public interface FragmentStrategy {
void showFragment(final int position);
}
}
How can i make this work?
In your case adding fragment will be the best solution.
create a fragment BlankFragment.java
public class BlankFragment extends Fragment {
public BlankFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank, container, false);
}
}
and create fragment_black.xml
<FrameLayout 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"
tools:context="com.above_inc.shyam.drawer.BlankFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
</FrameLayout>
now replace your method
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment = null;
if (id == R.id.nav_camera) {
// Handle the camera action
fragment = new BlankFragment();
} 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) {
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
add below code in your content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.above_inc.shyam.drawer.MainActivity"
tools:showIn="#layout/app_bar_main">
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
you can also add more fragment to other options same as camera in above code

Layout displaying ImageView at the bottom of the page

Im using a collapsing toolbar/scrollview in my activity. but my image (.jpg) always displays at the bottom of the page but i want it under the collapsing toolbar.
i have tried the following:
setting the gravity = top, match_parent, fill_parent, android:layout_below, changing the appbarlayout height but none have solved the problem stated.
heres a screenshot:
night_rui.xml
<tools: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="learn.navdrawbase.Rui">
<android.support.design.widget.AppBarLayout
android:id="#+id/MyAp"
android:layout_width="match_parent"
android:layout_height="56dp"
android:fitsSystemWindows="true"
android:theme="#style/AppTheme.AppBarOverlay"
android:layout_below="#+id/dhotelz">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapse_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/evebg">
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/dhotelz"
android:layout_above="#id/MyAp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="top"
android:src="#drawable/dhoteldesc"/>
</RelativeLayout>
</ScrollView>
</tools:android.support.design.widget.CoordinatorLayout>
Rui.java
package learn.navdrawbase;
import android.app.Activity;
import android.os.Bundle;
/**
* Created by User on 2/4/2016.
*/
public class Rui extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.night_rui);
}
}
BaseActivity.java if needed:
public abstract class BaseActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private Toolbar mActionBarToolbar;
private DrawerLayout mDrawerLayout;
protected NavigationView mNavigationView;
private ActionBarDrawerToggle mToggle;
/**
* Helper method that can be used by child classes to
* specify that they don't want a {#link Toolbar}
* #return true
*/
protected boolean useToolbar() {
return true;
}
/**
* Helper method to allow child classes to opt-out of having the
* hamburger menu.
* #return
*/
protected boolean useDrawerToggle() {
return true;
}
#Override
public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
getActionBarToolbar();
setupNavDrawer();
}//end setContentView
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Global methods as
/*
mImageLoader = new ImageLoader(this);
mHandler = new Handler();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.registerOnSharedPreferenceChangeListener(this);
...
*/
}
protected Toolbar getActionBarToolbar() {
if (mActionBarToolbar == null) {
mActionBarToolbar = (Toolbar) findViewById(R.id.toolbar);
if (mActionBarToolbar != null) {
// Depending on which version of Android you are on the Toolbar or the ActionBar may be
// active so the a11y description is set here.
mActionBarToolbar.setNavigationContentDescription(getResources()
.getString(R.string.navdrawer_description_a11y));
//setSupportActionBar(mActionBarToolbar);
if (useToolbar()) { setSupportActionBar(mActionBarToolbar);
} else { mActionBarToolbar.setVisibility(View.GONE); }
}
}
return mActionBarToolbar;
}
private void setupNavDrawer() {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
if (mDrawerLayout == null) {
return;
}
// use the hamburger menu
if( useDrawerToggle()) {
mToggle = new ActionBarDrawerToggle(
this, mDrawerLayout, mActionBarToolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
mDrawerLayout.setDrawerListener(mToggle);
mToggle.syncState();
}
else if(useToolbar() && getSupportActionBar() != null) {
// Use home/back button instead
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(ContextCompat
.getDrawable(this, R.drawable.abc_ic_ab_back_mtrl_am_alpha));
}
mNavigationView = (NavigationView) findViewById(R.id.nav_view);
mNavigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
switch (id) {
case R.id.nav_1:
createBackStack(new Intent(this, MyHome.class));
break;
case R.id.nav_2:
createBackStack(new Intent(this, MyTour.class));
break;
case R.id.nav_3:
createBackStack(new Intent(this, MyTranslator.class));
break;
case R.id.nav_4:
createBackStack(new Intent(this, MySettings.class));
break;
case R.id.nav_5:
createBackStack(new Intent(this, MyAbout.class));
break;
}
closeNavDrawer();
overridePendingTransition(R.anim.enter_from_left, R.anim.exit_out_left);
return true;
}
protected boolean isNavDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START);
}
protected void closeNavDrawer() {
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(GravityCompat.START);
}
}
/**
* Enables back navigation for activities that are launched from the NavBar. See
* {#code AndroidManifest.xml} to find out the parent activity names for each activity.
* #param intent
*/
private void createBackStack(Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
TaskStackBuilder builder = TaskStackBuilder.create(this);
builder.addNextIntentWithParentStack(intent);
builder.startActivities();
} else {
startActivity(intent);
finish();
}
}
}//end BaseActivity
Try to change your AppBarLayout height.
Add theme in your AppBarLayout.
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="256dp"
android:fitsSystemWindows="true"
android:theme="#style/AppTheme.AppBarOverlay">
So you need to use theme:
android:theme="#style/AppTheme.AppBarOverlay"
It's the code and works for me :
<?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="eb.collapsetoolbarlayout.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="256dp"
android:fitsSystemWindows="true"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapse_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
android:fitsSystemWindows="true">
<ImageView
android:id="#+id/bgheader"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:fitsSystemWindows="true"
android:background="#drawable/wallpaper2"
app:layout_collapseMode="pin" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="parallax"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>

Navigation Drawer is not opening on clicking menu icon

Navigation Drawer is not opening on clicking navigation icon(i.e 3 horizontal line on top left screen). On Lollipop it is working, but the problem is with Kitkat and jelly bean it is not working?
Styles.xml
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="windowActionBar">false</item>
<item name="android:windowActionBarOverlay">true</item>
<item name="drawerArrowStyle">#style/DrawerArrowStyle</item>
</style>
<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
<item name="spinBars">true</item>
<item name="color">#android:color/white</item>
</style>
AndroidManifes.xml
<application
android:name="com.volley_network_thread.AppController"
android:icon="#mipmap/ic_launcher"
android:allowBackup="true"
android:label="#string/app_name"
android:theme="#style/AppTheme">
......
......
......
......
</application>
toolbar.xml
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/app_theme_red_color"
android:elevation="4dp"
android:minHeight="?attr/actionBarSize"
android:title="#string/app_name">
activity_home.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="#layout/toolbar"></include>
</FrameLayout>
<LinearLayout
android:layout_width="300dp"
android:layout_height="fill_parent"
android:layout_gravity="start"
android:background="#FFF"
android:orientation="vertical">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="75dp"
android:layout_gravity="center"
android:background="#drawable/drawer_profile_bg">
<de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/imageView_round"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginTop="15dp"
android:src="#drawable/disp"
app:border_color="#color/gray_border"
app:border_width="2dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="ex : John Mathew"
android:textColor="#color/white"
android:textStyle="bold" />
</RelativeLayout>
<ListView
android:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFF"
android:choiceMode="singleChoice" />
<ExpandableListView
android:id="#+id/lvExp"
android:layout_width="match_parent"
android:layout_height="fill_parent" />
</LinearLayout>
Home.java
public class Home extends ActionBarActivity {
Toolbar toolbar;
final String[] data = {"Locate People", "Account Setting"};
DrawerLayout drawer;
ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
initialize();
setToolbar(0);
}
private void initialize() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
invalidateOptionsMenu();
}
}; // Drawer Toggle Object Made
drawer.setStatusBarBackgroundColor(getResources().getColor(R.color.app_theme_red_color));
drawer.setDrawerListener(mDrawerToggle); // Drawer Listener set to the Drawer toggle
mDrawerToggle.syncState(); // Finally we set the drawer toggle sync State
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
public void setToolbar(int position) {
if (position == 0) {
toolbar.setTitle("Establishemnt");
toolbar.setTitleTextColor(getResources().getColor(R.color.white));
} else if (position == 1) {
toolbar.setTitle("Settings");
toolbar.setTitleTextColor(getResources().getColor(R.color.white));
}
}
}
I face this problem today.
I think it's probably your DrawerLayout is at the root view, and you set the width and height = "match_parent".
In Lolipop, the tool bar is popup , so it's clickable. But in KitKat or lower version, it will click on the DrawerLayout, not the toolbar(the toolbar is behind the DrawerLayout).
My solution is to set MarginTop = "?attr/actionBarSize" in DrawerLayout.
Hope it's will helps you thought it's has been a long while : )
You codes seem a mess, take a look at mine, it works very well.
public class HomeActivity extends ActionBarActivity implements
DrawerCloseListener {
private Toolbar toolbar;
private DrawerLayout drawer;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = (Toolbar) findViewById(R.id.home_toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.app_name, R.string.app_name);
drawerToggle.setHomeAsUpIndicator(R.drawable.icon_nav);
drawer.setDrawerListener(drawerToggle);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
toolbar.setTitle("");
toolbar.setNavigationIcon(R.drawable.icon_nav);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
// 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.
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (drawer.isDrawerOpen(Gravity.LEFT | Gravity.START)) {
drawer.closeDrawers();
return;
}
super.onBackPressed();
}
#Override
public void onDrawerClose() {
// TODO Auto-generated method stub
if (drawer.isDrawerOpen(Gravity.LEFT | Gravity.START)) {
drawer.closeDrawers();
}
}
}

how to include items in navigation drawer

Here is MainActivity.java
public class MainActivity extends ActionBarActivity {
// inisiasi toolbar
private Toolbar toolbar;
// navigation drawer
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
String title = "My App";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
if (toolbar != null) {
toolbar.setTitle(title);
setSupportActionBar(toolbar);
}
initDrawer();
}
/**
* init navigation drawer thing
*/
private void initDrawer() {
//setup navigation drawer
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.txt_open, R.string.txt_close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
// when drawer closed
toolbar.setTitle(title);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
// when drawer open
toolbar.setTitle("Nav menu");
}
};
// setDrawerlisterner
drawerLayout.setDrawerListener(drawerToggle);
}
#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 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) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (drawerToggle.onOptionsItemSelected(item))
return true;
return super.onOptionsItemSelected(item);
}
}
and here is xml file layout view
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!-- Toolbar -->
<include layout="#layout/toolbar" />
<!-- content -->
<android.support.v4.widget.DrawerLayout
android:layout_width="match_parent"
android:id="#+id/drawerLayout"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:background="#fff"
android:layout_height="match_parent">
<TextView
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:textColor="#000"
android:text="Our Content"
android:layout_height="wrap_content" />
</RelativeLayout>
<!-- nav drawer -->
<LinearLayout
android:layout_gravity="start"
android:orientation="vertical"
android:background="#fff"
android:layout_width="280dp"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:textColor="#000"
android:text="Nav drawer"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
Does anyone know how to add a listview to navigation drawer. And i want to load a web page when user selects each item on navigation drawer into a fragment. I tried to implement a code from a sample but comes up with so many errors.
Well, there is nothing to afraid about NavigationDrawer. At first we may think that it is some special kind of activity and this and that. but it is so much simple.
Step 1 - Create xml file with 2 layouts
<FrameLayout>
//main screen contents
</FrameLayout>
<Linear/Relative/ListView/xyz>
// any layout that u want to be shown in navigation drawer
</Linear/Relative/ListView/xyz>
Step 2 - Define ur drawer in activity class with couple of codes
drawerLayout = (DrawerLayout) findViewById(R.id.NvDrawer);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close);
drawerLayout.setDrawerListener(drawerToggle);
and override this methods
#Override
public void onDrawerSlide(View view, float v) {
}
#Override
public void onDrawerOpened(View view) {
}
#Override
public void onDrawerClosed(View view) {
}
#Override
public void onDrawerStateChanged(int i) {
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
Step 3 - Add this code in onOptionsItemSelected
if (drawerToggle.onOptionsItemSelected(item)) {
return true;

Navigation drawer in android is not full screen

Since the google has introduced the navigation drawer, I tried to use this component to create a facebook-like menu. The problem is , the visual effect is seems to be different.
The google one has the action bar retain when the drawer is open while the facebook one does not.Instead, the whole screen has pushed to right side
I have found there are some lib can achieve this, but since I prefer not include third party lib in the project, are there any way to achieve this ? Thanks
Code based on navigation drawer tutorial
protected void setupMenu(List<String> list, final ListView menu) {
Adapter customAdapter = new Adapter(getActionBar().getThemedContext(),
R.layout.item, list);
menu.setAdapter(customAdapter);
menu.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int pos, long id) {
String selected = ((TextView) view.findViewById(R.id.itemTxt))
.getText().toString();
// define pass data
final Bundle bData = new Bundle();
bData.putString("itemSelect", selected);
drawer.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
FragmentTransaction tx = getSupportFragmentManager()
.beginTransaction();
tx.replace(R.id.mainContent, Fragment.instantiate(
MainActivity.this,
"com.example.utilities.ContentPage", bData));
tx.commit();
}
});
drawer.closeDrawer(menu);
}
});
}
Well creating a custom navigation drawer is the best solution for you.
I understand you do not want to use third party but this can be a quick solution to your problem Sliding Menu Lib link.
Hope this Helps.
<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"
>
<include
layout="#layout/nav_header_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.design.widget.NavigationView>
Remove the last two lines
in the default code
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer"
Here is a quick solution that worked for me :
<include
android:id="#+id/left_drawer"
android:orientation="vertical"
**android:layout_width="320dp"**
android:layout_height="match_parent"
android:layout_gravity="start"
layout="#layout/drawer"/>
Set width of included layout . For devices with different screen size you can dynamically set the width of this included layout .
All the best !!!!
If you will check source code of DrawerLayout, you will see, that resposnible for this minimum margin is the variable mMinDrawerMargin
So, there are atleast 2 solutions(tricks)
1. extend DrawerLayout and set this variable to 0 with reflection.
call this method from all constructors.
private void init() {
try {
Field declaredField = getClass().getSuperclass().getDeclaredField("mMinDrawerMargin");
declaredField.setAccessible(true);
declaredField.setInt(declaredField, 0);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
not so tricky
overryde onMeasure method like this
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// taken from parents logic
float density = this.getResources().getDisplayMetrics().density;
int minMargin = (int) (64.0F * density + 0.5F);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int newWidth = MeasureSpec.makeMeasureSpec(widthSize + minMargin, widthMode);
super.onMeasure(newWidth, heightMeasureSpec);
}
I also created sample project here https://bitbucket.org/wnc_21/fsnavigationdrawer
this problem is caused by margin so we have to reset the width :
i solved this problem by implementing DrawerListener and wrapping ListView inside a LinearLayout for making rooms for other views beside list view
here is my listener
public class NavigationDrawer implements DrawerLayout.DrawerListener {
private DrawerLayout mDrawerLayout;
protected boolean expanded = false;
NavigationDrawer(Activity activity) {
this.activity = activity;
}
public NavigationDrawer bindDrawerLayout(int id) {
mDrawerLayout = (DrawerLayout) activity.findViewById(id);
mDrawerLayout.setDrawerListener(this);
return this;
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
if (!expanded) {
Log.i("margin", "here we are");
LinearLayout layout = (LinearLayout) findViewById(R.id.left_drawer);
layout.getLayoutParams().width = getResources().getDisplayMetrics().widthPixels;
layout.requestLayout();
expanded = true;
}
}
#Override
public void onDrawerOpened(View drawerView) {
}
#Override
public void onDrawerClosed(View drawerView) {
}
#Override
public void onDrawerStateChanged(int newState) {
}
}
here is my layout :
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/application_drawer_layout"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#ffffff">
<FrameLayout
android:id="#+id/application_content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:id="#+id/left_drawer"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="start"
android:background="#000000"
android:orientation="vertical">
<ListView
android:id="#+id/application_left_drawer"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
If you want to implement like facebook sliding menu, then you to use androids SlidingPaneLayout instead of NavigationDrawer.
<android.support.v4.widget.SlidingPaneLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout android:layout_width="250dp"
android:layout_height="match_parent"
android:background="#CC00FF00" />
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="match_parent"
android:background="#CC0000FF" >
// add toolbar and other required layouts
</LinearLayout>
</android.support.v4.widget.SlidingPaneLayout>
add toolbar instead of actionbar and apply no actionbar theme.

Categories

Resources