How to create a custom navigation drawer in android - android

Hi I'm trying to create a navigation drawer similar to gmail app navigation drawer. I follow the developer site but it only specify about basic implementation. But I need to customize the navigation according to my specifications.
I need to add a header to categorize the list item in Drawer
I need a radio button to select some of my options
How can I do this?

The tutorial Android Custom Navigation Drawer (via archive.org) contains a basic and a custom project. The latter shows how to setup a Navigation Drawer as shown in the screenshot:
The source code of the projects (via archive.org) is available for download.
The is also the Navigation Drawer - Live-O project ...
The source code of the project is available on GitHub.
The MaterialDrawer library aims to provide the easiest possible implementation of a navigation drawer for your application. It provides a great amount of out of the box customizations and also includes an easy to use header which can be used as AccountSwitcher.
Please note that Android Studio meanwhile has a template project to create a Navigation Drawer Activity as shown in the screenshot.
This repository keeps track of changes being made to the template.

I used below layout and able to achieve custom layout in Navigation View.
<android.support.design.widget.NavigationView
android:id="#+id/navi_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start|top"
android:background="#color/navigation_view_bg_color"
app:theme="#style/NavDrawerTextStyle">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/drawer_header" />
<include layout="#layout/navigation_drawer_menu" />
</LinearLayout>
</android.support.design.widget.NavigationView>

The easier solution for me was:
Considerations:
This solution requires autogenerated Navigation Drawer Activity
provided by Android Studio.
Classes DrawerItem, CustomDrawerAdapter and layout custom_drawer_item.xml were taken from this tutorial.
1. Create this class for wrap the custom drawer item:
public class DrawerItem {
String ItemName;
int imgResID;
public DrawerItem(String itemName, int imgResID) {
super();
ItemName = itemName;
this.imgResID = imgResID;
}
public String getItemName() {
return ItemName;
}
public void setItemName(String itemName) {
ItemName = itemName;
}
public int getImgResID() {
return imgResID;
}
public void setImgResID(int imgResID) {
this.imgResID = imgResID;
}
}
2. Create custom layout (custom_drawer_item.xml) for your drawer items:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="#+id/itemLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:orientation="vertical"
android:layout_marginTop="0dp"
android:background="?android:attr/activatedBackgroundIndicator">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minHeight="55dp">
<ImageView
android:id="#+id/drawer_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/drawer_itemName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginBottom="1dp"
android:layout_marginTop="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#DADADC">
</View>
</LinearLayout>
</RelativeLayout>
3. Create your custom adapter:
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomDrawerAdapter extends ArrayAdapter<DrawerItem> {
Context context;
List<DrawerItem> drawerItemList;
int layoutResID;
public CustomDrawerAdapter(Context context, int layoutResourceID, List<DrawerItem> listItems) {
super(context, layoutResourceID, listItems);
this.context = context;
this.drawerItemList = listItems;
this.layoutResID = layoutResourceID;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
DrawerItemHolder drawerHolder;
View view = convertView;
if (view == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
drawerHolder = new DrawerItemHolder();
view = inflater.inflate(layoutResID, parent, false);
drawerHolder.ItemName = (TextView)view.findViewById(R.id.drawer_itemName);
drawerHolder.icon = (ImageView) view.findViewById(R.id.drawer_icon);
view.setTag(drawerHolder);
} else {
drawerHolder = (DrawerItemHolder) view.getTag();
}
DrawerItem dItem = (DrawerItem) this.drawerItemList.get(position);
drawerHolder.icon.setImageDrawable(view.getResources().getDrawable(
dItem.getImgResID()));
drawerHolder.ItemName.setText(dItem.getItemName());
return view;
}
private static class DrawerItemHolder {
TextView ItemName;
ImageView icon;
}
}
4. In autogenerated NavigationDrawerFragment class onCreateView method, replace the autogenerated adapter for this:
ArrayList<DrawerItem> dataList = new ArrayList<DrawerItem>();
dataList.add(new DrawerItem(getString(R.string.title_section1), R.drawable.ic_action_1));
dataList.add(new DrawerItem(getString(R.string.title_section2), R.drawable.ic_action_2));
dataList.add(new DrawerItem(getString(R.string.title_section3), R.drawable.ic_action_3));
mDrawerListView.setAdapter(new CustomDrawerAdapter(
getActivity(),
R.layout.custom_drawer_item,
dataList));
Remember replace R.string.title_sectionN and R.drawable.ic_action_N for your own resources.

You can easily customize the android Navigation drawer once you know how its implemented. here is a nice tutorial where you can set it up.
This will be the structure of your mainXML:
<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">
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Listview to display slider menu -->
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="right"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
android:background="#color/list_background"/>
</android.support.v4.widget.DrawerLayout>
You can customize this listview to your liking by adding the header. And radiobuttons.

Android Navigation Drawer using Activity
I just followed the example :http://antonioleiva.com/navigation-view/
You just need few Customization:
public class MainActivity extends AppCompatActivity {
public static final String AVATAR_URL = "http://lorempixel.com/200/200/people/1/";
private DrawerLayout drawerLayout;
private View content;
private Toolbar toolbar;
private NavigationView navigationView;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
toolbar = (Toolbar) findViewById(R.id.toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
initToolbar();
setupDrawerLayout();
content = findViewById(R.id.content);
drawerToggle = setupDrawerToggle();
final ImageView avatar = (ImageView) navigationView.getHeaderView(0).findViewById(R.id.avatar);
Picasso.with(this).load(AVATAR_URL).transform(new CircleTransform()).into(avatar);
}
private void initToolbar() {
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_black_24dp);
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
}
#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);
}
private void setupDrawerLayout() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id) {
case R.id.drawer_home:
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
finish();
break;
case R.id.drawer_favorite:
Intent j = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(j);
finish();
break;
}
return true;
}
});
}
Here is the xml Layout
<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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<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/ThemeOverlay.AppCompat.Light"
app:layout_scrollFlags="scroll|enterAlways|snap" />
</android.support.design.widget.AppBarLayout>
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/drawer"/>
Add drawer.xml in menu
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group
android:checkableBehavior="single">
<item
android:id="#+id/drawer_home"
android:checked="true"
android:icon="#drawable/ic_home_black_24dp"
android:title="#string/home"/>
<item
android:id="#+id/drawer_favourite"
android:icon="#drawable/ic_favorite_black_24dp"
android:title="#string/favourite"/>
...
<item
android:id="#+id/drawer_settings"
android:icon="#drawable/ic_settings_black_24dp"
android:title="#string/settings"/>
</group>
To open and close drawer add this values in string.xml
<string name="drawer_open">Open</string>
<string name="drawer_close">Close</string>
drawer.xml
enter code here
<ImageView
android:id="#+id/avatar"
android:layout_width="64dp"
android:layout_height="64dp"
android:layout_margin="#dimen/spacing_large"
android:elevation="4dp"
tools:src="#drawable/ic_launcher"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/email"
android:layout_marginLeft="#dimen/spacing_large"
android:layout_marginStart="#dimen/spacing_large"
android:text="Username"
android:textAppearance="#style/TextAppearance.AppCompat.Body2"/>
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="#dimen/spacing_large"
android:layout_marginStart="#dimen/spacing_large"
android:layout_marginBottom="#dimen/spacing_large"
android:text="username#mymail.com"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"/>

I need to add a header to categorize the list item in Drawer
Customize the listView or use expandableListView
I need a radio button to select some of my options
You can do that without modifying the current implementation of NavigationDrawer, You just need to create a custom adapter for your listView. You can add a parent layout as Drawer then you can do any complex layouts within that as normal.

Related

How to create an android drawer with custom icons on it?

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~

Unable to see navigation drawer

I have gone through similar questions and their solutions here, but I can't get past my issue after spending few hours on it. I looked at many solutions, tried them, but still can't get to see the navigation drawer on my screen. I will really appreciate if someone could tell me what am I missing here.
Thanks in advance.
Here's my xml :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="400dp"
android:layout_height="400dp"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/content_frame" >
</FrameLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Menu">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:textColor="#fff"
android:text="test"
android:id="#+id/text" />
</RelativeLayout>
<ListView
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="end"
android:choiceMode="singleChoice"
android:background="#fff"
android:id="#+id/left_drawer" >
</ListView>
</android.support.v4.widget.DrawerLayout>
Here's my Menu.java :
>public class Menu extends AppCompatActivity {
>
> public DrawerLayout dlayout;
> public ListView flist;
> public String[] menu;
> //public ArrayAdapter<String> mAdapter;
>
> #Override
> protected void onCreate(Bundle savedInstanceState) {
> super.onCreate(savedInstanceState);
> setContentView(R.layout.activity_menu);
>
> menu = getResources().getStringArray(R.array.nav_drawer_items);
> dlayout = (DrawerLayout) findViewById(R.id.drawer_layout);
> flist = (ListView) findViewById(R.id.left_drawer);
>
> flist.setAdapter(new ArrayAdapter<String>(this, R.layout.activity_menu, >R.id.text, menu));
> }
>}
I don't see any output.Screen output
seems that there should be problem in your layout file.
Remember that DrawerLayout allows maximum 2 child views. Have
a look at this Google Doc.
It should be like:
<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="#111"/>
</android.support.v4.widget.DrawerLayout>
<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">
<include
android:id="#+id/header"
layout="#layout/menu"/>
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:id="#+id/frame"
android:textSize="24sp"
android:gravity="center"
android:layout_marginTop="50dp"/>
<ListView
android:id="#+id/list_item"
android:layout_width="200dp"
android:layout_height="match_parent"
android:dividerHeight="1dp"
android:layout_gravity="left|start"
android:background="#ffeeeeee"/></android.support.v4.widget.DrawerLayout>
MainActivity.java
public class MainActivity extends Activity {
String[] names = {"android","java","spring","html"};
ListView list;
FrameLayout frame;
ActionBarDrawerToggle action;
DrawerLayout drawer;
Button but;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
frame = (FrameLayout) findViewById(R.id.frame);
list = (ListView) findViewById(R.id.list_item);
but = (Button) findViewById(R.id.menu);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, names);
list.setAdapter(adapter);
action = new ActionBarDrawerToggle(this, drawer, R.string.drawer_open, R.string.drawer_close) {
/* Called when drawer is closed */
public void onDrawerClosed(View view) {
//Put your code here
}
/* Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
//Put your code here
}
};
drawer.setDrawerListener(action);
but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer != null) {
if (drawer.isDrawerOpen(list)) {
drawer.closeDrawer(list);
} else {
drawer.openDrawer(list);
process();
}
}
}
});
}
private void process() {
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FragmentTransaction ft=getFragmentManager().beginTransaction();
switch (names[position])
{
case "android":
{
yourClass obj=new yourClass();
//ft.replace(R.id.frame,obj);
break
}
case "java":
{
yourClass obj=new yourClass();
//ft.replace(R.id.frame,obj);
break;
}
case "spring":
{
yourClass obj=new yourClass();
//ft.replace(R.id.frame,obj);
break;
}
case "html":
{
yourClass obj=new yourClass();
//ft.replace(R.id.frame,obj);
break;
}
default:
{
Toast.makeText(MainActivity.this,"you have to click another one",Toast.LENGTH_LONG).show();
}
}
ft.commitAllowingStateLoss();
list.setItemChecked(position, true);
drawer.closeDrawer(list);
}
});
}
}
menu.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"
tools:context=".MainActivity"
android:layout_height="wrap_content">
<Button
android:id="#+id/menu"
android:title="menu"
android:icon="#drawable/menu"
android:background="#drawable/menu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="#0a0a0a" /></LinearLayout>
You need to toggle the open/close of the drawer.
To do so, you can do the following :
1 - Implement the toggleDrawer method
public void toggleDrawer(boolean shouldBeVisible){
if(shouldBeVisible){
dlayout.openDrawer(dlayout);
} else {
dlayout.closeDrawers();
}
}
2 - Call it on onCreate (note : this is just for testing)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
toggleDrawer(View.VISIBLE);
}
3 - Like Daryl said, implement a button so you can actively toggle (open and close the drawer to your liking)
myButton = (Button) findViewById(R.id.myButton);
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
if(dlayout.getVisiblity() == View.VISIBLE) {
// drawer is visible -> close
toggleDrawer(false);
} else {
// drawer is gone/invisible -> open
toggleDrawer(true);
}
}
})
4 - (Make sure your DrawerLayout contains only 2 child views)
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.
Note : Forgot to add this but is indeed an invaluable reference (thanks to #Meet, upvoted)

In android how to set navigation drawer header image and name programmatically in class file?

In android studio 1.4.1, I have created new Navigation Drawer Project which is default.My issue is in this project there is nav_header_main.xml file which is for navigation header image and name. I want this image and name should be set programmatically in my main class activity. How to do this, I tried lot but the app crashes.
nav_header_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:id="#+id/headerView"
android:layout_height="#dimen/nav_header_height"
android:background="#drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:src="#android:drawable/sym_def_app_icon" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:text="Android Studio"
android:textAppearance="#style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="android.studio#android.com" />
</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
MainActivity.Class
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout headerImageView= (LinearLayout) findViewById(R.id.headerView);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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_view);
navigationView.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();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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) {
Toast.makeText(getApplicationContext(),"working",Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camara) {
// Handle the camera action
} 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) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View hView = navigationView.getHeaderView(0);
TextView nav_user = (TextView) hView.findViewById(R.id.nav_name);
nav_user.setText(user);
As mentioned in the bug 190226, Since version 23.1.0 getting header layout view with:
navigationView.findViewById(R.id.navigation_header_text) no longer works.
A workaround is to inflate the headerview programatically and find view by ID from the inflated header view.
For example:
View headerView = navigationView.inflateHeaderView(R.layout.navigation_header);
headerView.findViewById(R.id.navigation_header_text);
Ideally there should be a method getHeaderView() but it has already been proposed, let's see and wait for it to be released in the feature release of design support library.
don't add header in xml add using code by inflating layout
View hView = navigationView.inflateHeaderView(R.layout.nav_header_main);
ImageView imgvw = (ImageView)hView.findViewById(R.id.imageView);
TextView tv = (TextView)hView.findViewById(R.id.textview);
imgvw .setImageResource();
tv.settext("new text");
In Kotlin
val hView = nav_view.getHeaderView(0)
val textViewName = hView.findViewById(R.id.textViewName) as TextView
val textViewEmail = hView.findViewById(R.id.textViewEmail) as TextView
val imgvw = hView.findViewById(R.id.imageView) as ImageView
imgvw.setImageResource(R.drawable.ic_menu_gallery)
First you need to access the navigation drawer in your MainActivity(or the calling activity) like this:
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
Then you need to remove the header layout from the activity_main.xml because the layout will be inflated programatically in the MainActivity. Your activity_main.xml should look like this:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
Then in your MainActivity, we inflate the nav_header_main layout and get access to its views, in this case the ImageView and TextView
//inflate header layout
View navView = navigationView.inflateHeaderView(R.layout.nav_header_main);
//reference to views
ImageView imgvw = (ImageView)navView.findViewById(R.id.imageView);
TextView tv = (TextView)navView.findViewById(R.id.textview);
//set views
imgvw.setImageResource(R.drawable.your_image);
tv.setText("new text");
navigationView.setNavigationItemSelectedListener(this);
You can read more here
val navigationView: NavigationView = findViewById(R.id.nv)
val header: View = navigationView.getHeaderView(0)
val tv: TextView = header.findViewById(R.id.profilename)
tv.text = "Your_Text"
This will fix your problem <3
Here is my code
below perfectly working
Do not add the header in NavigationView
tag in activity_main.xml
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="#menu/activity_main_drawer"
app:itemBackground="#drawable/active_drawer_color" />
add header programmatically with below code
View navHeaderView = navigationView.inflateHeaderView(R.layout.nav_header_main);
headerUserName = (TextView) navHeaderView.findViewById(R.id.nav_header_username);
headerMobileNo = (TextView) navHeaderView.findViewById(R.id.nav_header_mobile);
headerMobileNo.setText("+918861899697");
headerUserName.setText("Anirudh R Huilgol");
nav = ( NavigationView ) findViewById( R.id.navigation );
if( nav != null ){
LinearLayout mParent = ( LinearLayout ) nav.getHeaderView( 0 );
if( mParent != null ){
// Set your values to the image and text view by declaring and setting as you need to here.
SharedPreferences prefs = getSharedPreferences("user_data", MODE_PRIVATE);
String photoUrl = prefs.getString("photo_url", null);
String user_name = prefs.getString("name", "User");
if(photoUrl!=null) {
Log.e("Photo Url: ", photoUrl);
TextView userName = mParent.findViewById(R.id.user_name);
userName.setText(user_name);
ImageView user_imageView = mParent.findViewById(R.id.avatar);
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.ic_user_24dp);
requestOptions.error(R.drawable.ic_user_24dp);
Glide.with(this).load(photoUrl)
.apply(requestOptions).thumbnail(0.5f).into(user_imageView);
}
}
}
Hope this helps.
If you're using bindings you can do
val headerView = binding.navView.getHeaderView(0)
val headerBinding = NavDrawerHeaderBinding.bind(headerView)
headerBinding.textView.text = "Your text here"
EDIT : Works with design library upto 23.0.1 but doesn't work on 23.1.0
In main layout xml you will have NavigationView defined, in that use app:headerLayout to set the header view.
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_drawer_header"
app:menu="#menu/navigation_drawer_menu" />
And the #layout/nav_drawer_header will be the place holder of the image and texts.
nav_drawer_header.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="170dp"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/headerRelativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:src="#drawable/background" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="#dimen/action_bar_size"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#40000000"
android:gravity="center"
android:orientation="horizontal"
android:paddingBottom="5dp"
android:paddingLeft="16dp"
android:paddingRight="10dp"
android:paddingTop="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="35dp"
android:orientation="vertical"
android:weightSum="2">
<TextView
android:id="#+id/navHeaderTitle"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#android:color/white" />
<TextView
android:id="#+id/navHeaderSubTitle"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#android:color/white" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
And in your main class, you can take handle of Imageview and TextView as like normal other views.
TextView navHeaderTitle = (TextView) findViewById(R.id.navHeaderTitle);
navHeaderTitle.setText("Application Name");
TextView navHeaderSubTitle = (TextView) findViewById(R.id.navHeaderSubTitle);
navHeaderSubTitle.setText("Application Caption");
Hope this helps.
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.addHeaderView(yourview);
I know this is an old post but i am sure that this might help someone down the road.
You can simply get the headerView element of the Navigation view by doing this:
NavigationView mView = ( NavigationView ) findViewById( R.id.nav_view );
if( mView != null ){
LinearLayout mParent = ( LinearLayout ) mView.getHeaderView( 0 );
if( mParent != null ){
// Set your values to the image and text view by declaring and setting as you need to here.
}
}
I hope that this helps someone.
Also you can use Kotlinx features
val hView = nav_view.getHeaderView(0)
hView.textViewName.text = "lorem ipsum"
hView.imageView.setImageResource(R.drawable.ic_menu_gallery)
FirebaseAuth firebaseauth = FirebaseAuth.getInstance();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); //displays text of header of nav drawer.
View headerview = navigationView.getHeaderView(0);
TextView tt1 = (TextView) headerview.findViewById(R.id.textview_username);
tt1.setText(firebaseauth.getCurrentUser().getDisplayName());//username of logged in user.
TextView tt = (TextView) headerview.findViewById(R.id.textView_emailid);
tt.setText(firebaseauth.getCurrentUser().getEmail()); //email id of logged in user.
final ImageView img1 = (ImageView) headerview.findViewById(R.id.imageView_userimage);
Glide.with(getApplicationContext())
.load(firebaseauth.getCurrentUser().getPhotoUrl()).asBitmap().atMost().error(R.drawable.ic_selfie_point_icon) //asbitmap after load always.
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
img1.setImageBitmap(resource);
}
});
I have made this code by myself with some logic...Its 100% working.....pls do upvote my ans.
The textview and imageview are from #layout/nav_header_main.xml
It's and old post, but it's new for me. So, it is straight forward!
In this part of the code:
public boolean onNavigationItemSelected(MenuItem item) {
}
, I bound an ImageView to the LinearLayout, which contains the ImageView from the example, listed below. Mind: it's the same code you get when you start a new project, and choose the template "Navigation Drawer Activity":
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:src="#android:drawable/sym_def_app_icon" />
I gave the LinearLayout and ID, inside nav_header_main.xml (in my case I chose 'navigation_header_container' , so it went this way:
LinearLayout lV = (LinearLayout) findViewById(R.id.navigation_header_container);
ivCloseDrawer = (ImageView) lV.findViewById(R.id.imageView);
ivCloseDrawer.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
drawer.closeDrawer(GravityCompat.START);
}
});
Note: I have a private ImageView ivCloseDrawer declared at the top, before onCreate (MainActivity).
Here is the method you can use to get header view and set data accourdingly
val headerView: View? = navigationView.getHeaderView(0) // Index of the added headerView
// Now you can access child views of the header view
val titleTextView: TextView? = headerView?.findViewById(R.id.titleTextView)
For those who use KOTLIN :
val headerview = binding.navDrawer.getHeaderView(0)
val NavDrawheaderviewRef = NavdrawerHeaderLayoutBinding.bind(headerview)
NavDrawheaderviewRef.btnSearch.setOnClickListener
{
Toast.make(this , "Hii buddy",LENGTH_SHORT).show()
}
Here :
navDrawer = id of my Navigation Drawer
NavdrawerHeaderLayoutBinding
= a func which is used to get a ref of header layout.
btnSearch = a button present in the header layout

Facebook Login Button Appears Over Navigation Drawer

I'm trying to implement the facebook login tutorial, along with a navigation drawer. I managed to create the drawer successfully, but when I tried it on the emulator, the facebook login button appears over the drawer, even though it is part of another layout (fragment).
Here's my MainActivity layout:
<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">
<!-- 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="#ff939393"
android:dividerHeight="1dp"
android:background="#ff333333"/>
</android.support.v4.widget.DrawerLayout>
And here is my fragment layout:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/facebook_login_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1">
<com.facebook.widget.LoginButton android:id="#+id/authButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center|center_horizontal"
android:layout_marginTop="40dp" />
<TextView
android:id="#+id/textView"
android:layout_width="312dp"
android:layout_height="101dp"
android:text="#string/please_login_with_facebook"
android:padding="10dp"
android:textStyle="bold"
android:typeface="serif"
android:singleLine="false"
android:layout_weight="0.13"
android:textAlignment="center"
android:gravity="center"
android:layout_gravity="center_horizontal"
android:layout_marginTop="150dp" />
<Button android:id="#+id/connection_settings_button"
android:layout_width="188dp"
android:layout_height="wrap_content"
android:text="#string/turn_on_internet_button"
android:layout_gravity="center"
android:layout_marginTop="36dp"
android:visibility="invisible" />
</FrameLayout>
And this is the MainActivity class:
public class MainActivity extends ActionBarActivity {
private String[] mDrawerTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private FacebookLoginFragment fbFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity_layout);
mDrawerTitles = getResources().getStringArray(R.array.nav_drawer_items);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, mDrawerTitles));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
fbFragment = new FacebookLoginFragment();
getSupportFragmentManager()
.beginTransaction()
.add(android.R.id.content, fbFragment)
.commit();
} else {
// Or set the fragment from restored state info
fbFragment = (FacebookLoginFragment) getSupportFragmentManager().findFragmentById(android.R.id.content);
}
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mDrawerTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I'll post more code if necessary. Unfortunately I still don't have the reputation to post images, but here is my problem. Any help is very appreciated!
When you FragmentTransaction.replace your FacebookLoginFragment, don't use the id android.R.id.content. Instead use the id of the FrameLayout that acts as the content of your DrawerLayout, which in this case is R.id.content_frame.

NavigationDrawer and ViewPager in the same Activity in Android

I am trying to create a NavigationDrawer as well as having a ViewPager with sliding tabs in an activity using ActionBarSherlock. I have the tabs and I have created layouts for the view pager and the drawer layout. I know that what I have is that the viewpager layout and drawerlayout are in seperate files and they should probably be in the same file to find the view. Although I do not know how to do this with the code that I have.
I have done a lot of research as to how to do this and the standard pattern is to not do this, although as many people have pointed out, Google Play Music does this. I want my application to look like that and I know that there is a workaround as people have suggested. I am just unsure on how the workaround works with ActionBarSherlock and the code that I currently have implemented. Please can anyone help me with this. Thank you in advance.
Here is my activity code:
public class SlidingTabsActivity extends SherlockFragmentActivity
{
private ViewPager viewPager;
private TabsAdapter tabsAdapter;
private ActionBar actionBarTabs;
/* Navigation drawer */
private DrawerLayout drawerLayout;
private ListView drawerListView;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
viewPager = new ViewPager(this);
viewPager.setId(R.id.pager);
setContentView(viewPager);
/* Navigation Drawer */
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerListView = (ListView) findViewById(R.id.left_drawer);
System.out.println("Drawer Layout test:" + drawerLayout.getId());
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
drawerListView.setAdapter(new ArrayAdapter<String>(this, R.layout.navigation_drawer_list_item, R.array.navigation_drawer_list));
drawerListView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
// TODO Auto-generated method stub
}
});
actionBarTabs = getSupportActionBar();
actionBarTabs.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBarTabs.setDisplayHomeAsUpEnabled(true);
actionBarTabs.setHomeButtonEnabled(true);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close)
{
public void onDrawerClosed(View view)
{
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView)
{
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
drawerLayout.setDrawerListener(drawerToggle);
tabsAdapter = new TabsAdapter(this, viewPager); // Declares the tabs adapter class with the view pager view
/* Adds fragments to the tabs adapter */
tabsAdapter.addTab(actionBarTabs.newTab().setText("PV"), Fragment_1.class, null);
tabsAdapter.addTab(actionBarTabs.newTab().setText("CONFIG"), Fragment_2.class, null);
tabsAdapter.addTab(actionBarTabs.newTab().setText("DIAG"), Fragment_3.class, null);
}
Here is my DrawerLayout layout xml code:
<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">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<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="#111"/>
</android.support.v4.widget.DrawerLayout>
And here is my ViewPager layout xml code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SlidingTabsActivity" >
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/pager" />
</RelativeLayout>
Firstly, your Activity has both Navigation Drawer and ViewPager, but I saw you put the layout descriptions in different xml files. But, you must put only one xml file for your Activity.
Considering this, the key point now is: "how to declare DrawerLayout and ViewPager in the same xml?". If you put in wrong order it won't work (I had this same problem, that's why I'm alerting you). So, the answer is to declare the DrawerLayout as root and inside it, the ViewPager, and later, after closing the ViewPager "tag", you declare the ListView of DrawerLayout.
An example:
<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">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
<ListView android:id="#+id/drawer_list"
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" />
</android.support.v4.widget.DrawerLayout>
I hope the answer helps you.

Categories

Resources