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)
Related
I'm working on an app but I have some troubles with drawer layout. I always getting the error message like I mentioned in the title but I have no such Gravity with LEFT value. All I have are gravities with END values and that's all.
Here is my Java code:
public class HomeActivity extends AppCompatActivity {
private ActionBarDrawerToggle toggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar mainToolBar =findViewById(R.id.main_page_toolbar);
DrawerLayout mainDrawerLayout = findViewById(R.id.main_page_drawer_layout);
NavigationView mainNavigationView = findViewById(R.id.main_page_navigation_view);
setSupportActionBar(mainToolBar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setHomeButtonEnabled(true);
toggle = new ActionBarDrawerToggle(this,mainDrawerLayout,mainToolBar,R.string.openDrawer,R.string.closeDrawer);
mainDrawerLayout.addDrawerListener(toggle);
toggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
toggle.onConfigurationChanged(newConfig);
}
}
And here is my XML code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:openDrawer="end"
tools:context=".Activities.HomeActivity"
android:id="#+id/main_page_drawer_layout"
android:fitsSystemWindows="true">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="#layout/home_main_page"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<com.google.android.material.navigation.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="end"
app:headerLayout="#layout/home_side_menu_header_layout"
app:menu="#menu/home_side_menu"
android:layoutDirection="rtl"
android:id="#+id/main_page_navigation_view"/>
You need to handle navigation click on Toolbar like below:
mainToolBar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mainDrawerLayout.isDrawerOpen(GravityCompat.END))
mainDrawerLayout.closeDrawer(GravityCompat.END);
else
mainDrawerLayout.openDrawer(GravityCompat.END);
}
});
Also don't forgot to close drawer whenever needed like below:
mainDrawerLayout.closeDrawer(GravityCompat.END)
I am having some difficulties when trying to use a navigation drawer and fragment together.
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".GoogleMap" >
<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="#666"
android:dividerHeight="1dp"
android:background="#333"
android:paddingLeft="15sp"
android:paddingRight="15sp"
/>
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
So the problem that I am facing is the navigation drawer only shows the content for a short moment when I rotate the device either from portrait to landscape or the other way around. The navigation drawer will remains empty if I do not tilt the device.
The fragment is basically a so-called div to show a map. Then when I click on the navigation drawer, it will be on the top of the map fragment. I wonder which part of my layout went wrong and causing this problem.
Thanks in advance.
Edited Portion
<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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!-- 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>
GoogleMap.java
public class GoogleMap extends FragmentActivity {
// Google Map
private com.google.android.gms.maps.GoogleMap map;
private String[] drawerListViewItems;
private DrawerLayout drawerLayout;
private ListView drawerListView;
private ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
// get list items from strings.xml
drawerListViewItems = getResources().getStringArray(R.array.items);
// get ListView defined in activity_main.xml
drawerListView = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
drawerListView.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_listview_item, drawerListViewItems));
// App Icon
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
drawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
);
// Set actionBarDrawerToggle as the DrawerListener
drawerLayout.setDrawerListener(actionBarDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
// just styling option add shadow the right edge of the drawer
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
drawerListView.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// call ActionBarDrawerToggle.onOptionsItemSelected(), if it returns true
// then it has handled the app icon touch event
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
actionBarDrawerToggle.syncState();
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
Toast.makeText(GoogleMap.this, ((TextView)view).getText(), Toast.LENGTH_LONG).show();
//Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr=1.3564 ,103.8311&daddr=1.3426 ,103.9254"));
//startActivity(i);
drawerLayout.closeDrawer(drawerListView);
}
}
/**
* function to load map. If map is not created it will create it for you
* */
private void initilizeMap() {
if (map == null) {
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(
R.id.map)).getMap();
map.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(1.32814,103.80679) , 11.0f) );
// check if map is created successfully or not
if (map == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
There is one Problem with your Layout(i don't know others!) which is using DrawerLayout inside a LinearLayout , DrawerLayout should be root view in your Layout file.
You have 3 views directly inside your drawerlayout. The drawer must only have 2 views immediately inside it. I'd recommend wrapping the fragment and framelayout inside a linearlayout or relativelayout. Either that or nest the fragment inside the framelayout
You should code like this:
<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" />
<!-- 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>
Edit:
And in your Activity set the fragment in this FrameContent.
In your onCreate() add this line
if (savedInstanceState == null) {
initilizeMap();
}
I added navigation drawer to my application. Everything works fine, but now I am trying to add a simple textView to menu, and am not succeeding. The problem is the fact that text is hidden underneath actionBar itself. Even 50dp margin from top isn't enough.
Do you have any tips on how to fix this issue?
My main activity:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/container"
android:fitsSystemWindows="true"
android:clipToPadding="false"/>
<!-- The navigation drawer -->
<FrameLayout
android:id="#+id/left_drawer"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#color/dark_brown">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:textSize="40dp"
android:textColor="#ffffff"
android:id="#+id/textView"
android:layout_marginTop="50dp"
android:layout_marginLeft="20dp"
android:gravity="center_vertical"/>
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
And my main activities class:
public class MainActivity extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private DatabaseHandler database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Handle application side menu
sideMenu();
// Set tint for android bar (only for KitKat version)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
SystemBarTintManager tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarTintResource(R.color.action_bar_bg);
}
// Create system objects
database = new DatabaseHandler(this);
final Statistics statistic = new Statistics(database);
// Create main fragment and point app to it
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new MainFragment(database, statistic))
.commit();
}
}
private void sideMenu() {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this, // host Activity
mDrawerLayout, // DrawerLayout object
R.drawable.ic_drawer, // nav drawer icon to replace 'Up' caret
R.string.drawer_open, // "open drawer" description
R.string.drawer_close // "close drawer" description
) {
// Called when a drawer has settled in a completely closed state.
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(R.string.drawer_close);
}
// Called when a drawer has settled in a completely open state.
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(R.string.drawer_open);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
super.onDestroy();
database.closeDatabase();
}
}
You want to assign fitsSystemWindows and clipToPadding to the Navigation Drawer fragment (most probably the ListView)
Something like this -
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#cccc"
android:fitsSystemWindows="true"
android:clipToPadding="false"
/>
But in your case, you are using the FrameLayout on the activity_main itself to populate the Drawer contents. So you have to apply these two properties to the FrameLayout
<FrameLayout
android:id="#+id/left_drawer"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:fitsSystemWindows="true"
android:clipToPadding="false"
android:background="#color/dark_brown">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:textSize="40dp"
android:textColor="#ffffff"
android:id="#+id/textView"
android:gravity="center_vertical"/>
</FrameLayout>
Also, notice, you don't need following to your TextView anymore.
android:layout_marginTop="50dp"
android:layout_marginLeft="20dp"
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.
I try to implement the latest drawer layout from support library 13.
With the following code, the drawer is always showing below the gridview. Even I try to call bringToFront() still not working. Can help to find what's wrong? Thanks.
activity_main.xml
<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>
member_home_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<GridView
android:id="#+id/member_home_thumbnail_grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="0dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="0dp" >
</GridView>
</LinearLayout>
The main activity:
public class BaseRootActivity extends BaseActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private String[] mMainMenus;
public ListView getDrawerListView() {
return this.mDrawerList;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMainMenus = this.getResources().getStringArray(R.array.main_menu_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) this.findViewById(R.id.left_drawer);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mMainMenus));
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
getActionBar().setTitle("actionbar title");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle("drawer title");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
...
in main fragment
public class MemberHomeFragment extends Fragment implements OnItemClickListener {
private GridView mGridListView;
private UserThumbnailAdapter memberAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.member_home_layout, container, false);
mGridListView = (GridView) rootView.findViewById(R.id.member_home_thumbnail_grid);
mGridListView.setOnItemClickListener(this);
memberAdapter = new UserThumbnailAdapter(this.getActivity(), null);
mGridListView.setAdapter(memberAdapter);
this.startLoading(); // load thumbnails
return rootView;
}
So this isn't a problem with the way you are using the drawer layout as I mentioned earlier. It's a problem with the way you are using fragments. The way the FragmentManager works is you create a fragment transaction, and you tell the fragment transaction a set piece of work and then you commit it, so that it all happens at once.
When you add, remove, or in your case Replace a fragment you have to tell the FragmentManager where to put your fragment, and you were giving it the wrong location. You were telling it to put your fragment inside android.R.id.content, a place that ALL of the content on the screen lives inside. You only want to add a fragment to one your own containers. The fact that the ID you specified (android.R.id.content) begins with 'android', is a big giveaway that it is the android systems, and not yours.
You instead want to put it in the location inside of your navigation drawer that you specified, which is R.id.content_frame. You can see how you specified that in your xml above, which I will copy here for you:
<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"/>
I cannot understand but here is the issue:
As #spierce7 pointed out, the way I call fragment replacement is not correct (but why?)
My code is:
getFragmentManager().beginTransaction().replace(android.R.id.content, new MemberHomeFragment()).commit();
and when I changed to:
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, new MemberHomeFragment()).commit();
It works.