I want to add multiple header in drawerlist. Right now I am able to add just one header. How to I add header (like categories) in my drawer list?
MainActivity.java
package com.pixalstudio.javaclasses;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements AdapterView.OnItemClickListener {
private Toolbar toolbar;
ListView mDrawerList;
DrawerLayout mDrawerLayout;
ActionBarDrawerToggle mDrawerToggle;
String[] mDrawerListItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConnectivityManager cManager = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cManager.getActiveNetworkInfo();
if (nInfo != null && nInfo.isConnected()) {
Toast.makeText(this, "Newtwrok Available", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Network Not Available", Toast.LENGTH_LONG).show();
}
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
LayoutInflater inflater = getLayoutInflater();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mDrawerList = (ListView) findViewById(R.id.drawerList);
mDrawerListItems = getResources().getStringArray(R.array.drawer_list);
ViewGroup header_news = (ViewGroup) inflater.inflate(R.layout.nav_header, mDrawerList, false);
mDrawerList.addHeaderView(header_news, null, false);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mDrawerListItems));
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int editPosition = position + 1;
Toast.makeText(MainActivity.this, "You Have Selected " + editPosition, Toast.LENGTH_SHORT).show();
mDrawerLayout.closeDrawer(mDrawerList);
}
});
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
toolbar,
R.string.drawer_open,
R.string.drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
syncState();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
syncState();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle.syncState();
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.syncState();
}
#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) {
switch (item.getItemId()) {
case android.R.id.home: {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int editPosition = position + 1;
Toast.makeText(MainActivity.this, "You Have Selected " + editPosition, Toast.LENGTH_SHORT).show();
mDrawerLayout.closeDrawer(mDrawerList);
}
}
activity_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"
android:orientation="vertical">
<include
android:id="#+id/app_bar"
layout="#layout/app_bar">
</include>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawerLayout"
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">
</FrameLayout>
<ListView
android:id="#+id/drawerList"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#CE93D8">
</ListView>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
nav_header.xml
android:id="#+id/head1"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimaryDark"
android:padding="16dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
android:orientation="vertical"
android:gravity="bottom">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Header 1"
android:textColor="#android:color/white"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"/>
</LinearLayout>
I tried searching for the solution but every time I mess up with the code. Can someone give me perfect solution for this with code? Thank you in advance. :)
This is how I want like Title 1 and Title 2
Related
I have an activity which displays an AppToolbar alongside a RecyclerView which is located below the Toolbar. Every row of the RecyclerView is a CardView. My problem is that the RecyclerView doesn't scroll at all. It seems that it doesn't receive any gesture callbacks.
Here is my main layout 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"
android:fitsSystemWindows="true"
android:background="#color/colorActivityBackground"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rv"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbars="vertical"
android:fadeScrollbars="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
<include layout="#layout/tool_bar" />
<include layout="#layout/nav_drawer_layout" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/fab_margin"
android:src="#drawable/ic_add"
app:layout_anchor="#id/rv"
app:layout_anchorGravity="bottom|end" />
</android.support.design.widget.CoordinatorLayout>
Edit: Here is the tool bar code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="false"
android:theme="#style/AppTheme.AppBarOverlay"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:elevation="4dp"
android:theme="#style/AppTheme.AppBarOverlay"
app:layout_collapseMode="pin"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
Here is also my nav drawer layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize">
<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 -->
<android.support.v7.widget.RecyclerView
android:id="#+id/right_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="#99ccff" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
And here is my Main Activity where I populate my recycler view:
package bikurim.silverfix.com.bikurim;
import android.app.SearchManager;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import bikurim.silverfix.com.bikurim.adapters.MenuDrawerAdapter;
import bikurim.silverfix.com.bikurim.adapters.RecyclerViewAdapter;
import bikurim.silverfix.com.bikurim.items.FamilyItem;
public class MainActivity extends AppCompatActivity {
private ArrayList<FamilyItem> families = new ArrayList<FamilyItem>();
private ArrayList<bikurim.silverfix.com.bikurim.items.MenuItem> items = new ArrayList<bikurim.silverfix.com.bikurim.items.MenuItem>();
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private RecyclerView recyclerView, menuView;
private RecyclerViewAdapter adapter;
private MenuDrawerAdapter navAdapter;
private SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_families);
// Setting up the tool bar
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Setting up the main lists and their adapters
fillList();
createMenuItems();
recyclerView = (RecyclerView) findViewById(R.id.rv);
menuView = (RecyclerView) findViewById(R.id.right_drawer);
adapter = new RecyclerViewAdapter(families);
navAdapter = new MenuDrawerAdapter(items);
// Default Animator
DefaultItemAnimator animator = new DefaultItemAnimator();
recyclerView.setItemAnimator(animator);
menuView.setItemAnimator(animator);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
menuView.setLayoutManager(new LinearLayoutManager(this));
menuView.setAdapter(navAdapter);
Log.d("Menu Items Count:", ""+navAdapter.getItemCount());
// Setting up the navigation drawer side-menu with DrawerLayout
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer is in closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(R.string.app_name);
}
/** Called when a drawer is in open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(R.string.drawer_name);
}
};
drawerLayout.addDrawerListener(drawerToggle);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Does absolutly nothing, yet!", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
private void fillList() {
families.add(new FamilyItem("Ohayon", "12:36"));
families.add(new FamilyItem("Zohar", "14:23"));
families.add(new FamilyItem("Lasry", "15:55"));
families.add(new FamilyItem("Zambuzak", "17:45"));
families.add(new FamilyItem("Cohen", "11:33"));
families.add(new FamilyItem("Tapera", "09:25"));
families.add(new FamilyItem("Ochuya", "09:25"));
families.add(new FamilyItem("Konichiwua", "09:25"));
families.add(new FamilyItem("Kontaktiwa", "09:25"));
}
private void createMenuItems() {
items.add(new bikurim.silverfix.com.bikurim.items.MenuItem(R.drawable.about, "עזרה"));
items.add(new bikurim.silverfix.com.bikurim.items.MenuItem(R.drawable.settings, "הגדרות"));
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_families, menu);
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
adapter.getFilter().filter(query);
return true; // handled
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return true;
}
});
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 (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
//noinspection SimplifiableIfStatement
if (id == R.id.action_search) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I have created a Navigation Drawer following a tutorial, but now I have a problem. How can I use it in multiple activities without duplicating the code?
I tried extending the main activity, but I found some problems with Toolbar. There's some other way?
Thanks, this is my code.
MainActivity.java
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
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.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
class NavItem {
String mTitle;
int mIcon;
public NavItem(String title, int icon) {
mTitle = title;
mIcon = icon;
}
}
class DrawerListAdapter extends BaseAdapter {
Context mContext;
ArrayList<NavItem> mNavItems;
public DrawerListAdapter(Context context, ArrayList<NavItem> navItems) {
mContext = context;
mNavItems = navItems;
}
public int getCount() {
return mNavItems.size();
}
public Object getItem(int position) {
return mNavItems.get(position);
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.drawer_item, parent, false);
}
else {
view = convertView;
}
TextView titleView = (TextView) view.findViewById(R.id.title);
ImageView iconView = (ImageView) view.findViewById(R.id.icon);
titleView.setText( mNavItems.get(position).mTitle );
iconView.setImageResource(mNavItems.get(position).mIcon);
return view;
}
}
ListView mDrawerList;
RelativeLayout mDrawerPane;
private static String TAG = MainActivity.class.getSimpleName();
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
ArrayList<NavItem> mNavItems = new ArrayList<>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mNavItems.add(new NavItem(getString(R.string.home), R.drawable.ic_action_home));
mNavItems.add(new NavItem(getString(R.string.company), R.drawable.ic_action_company));
mNavItems.add(new NavItem(getString(R.string.services), R.drawable.ic_action_services));
mNavItems.add(new NavItem(getString(R.string.solutions), R.drawable.ic_action_solutions));
mNavItems.add(new NavItem(getString(R.string.case_history), R.drawable.ic_action_case_history));
mNavItems.add(new NavItem(getString(R.string.contacts), R.drawable.ic_action_contacts));
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mDrawerPane = (RelativeLayout) findViewById(R.id.drawerPane);
mDrawerList = (ListView) findViewById(R.id.navList);
DrawerListAdapter adapter = new DrawerListAdapter(this, mNavItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mDrawerLayout.closeDrawer(mDrawerPane);
if (position == 0) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
} else if (position == 1) {
Intent intent = new Intent(getApplicationContext(), CompanyActivity.class);
startActivity(intent);
}
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
Log.d(TAG, "onDrawerClosed: " + getTitle());
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
return mDrawerToggle.onOptionsItemSelected(item);
}
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
}
activity_main.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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior" >
<ImageView
android:contentDescription="#string/app_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/logo" />
</RelativeLayout>
<include layout="#layout/side_menu" />
<include layout="#layout/toolbar" />
</android.support.design.widget.CoordinatorLayout>
side_menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize" >
<RelativeLayout
android:id="#+id/mainContent"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<RelativeLayout
android:layout_width="280dp"
android:layout_height="match_parent"
android:id="#+id/drawerPane"
android:layout_gravity="start">
<ListView
android:id="#+id/navList"
android:layout_width="280dp"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
android:background="#FFF" />
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
toolbar.xml:
<android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay" >
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
Create a baseactivity with your drawer inside and then extend base activity to all activities in which you want drawer.
And instead of calling setcontentview() in oncreate inheriting activities use layout inflator
Check this post
How to Display Navigation Drawer in all activities?
Here is part of real code from my project. #Bind is from awesome Butterknife library. AbstractToolbarActivity it's a sub class of the AppCompatActivity that follows the same logic (avoiding duplicating code of initializing toolbars)
public abstract class AbstractDrawerActivity extends AbstractToolbarActivity {
#Bind(R.id.drawer_layout) DrawerLayout mDrawerLayout;
ActionBarDrawerToggle mDrawerToggle;
protected void initDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.drawer_open,
R.string.drawer_close);
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
}
#Override protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
initDrawer();
mDrawerToggle.syncState();
}
#OnClick(R.id.drawer_user_name) protected void openProfile() {
final Intent profile = new Intent(this, ProfileActivity.class);
startActivity(profile);
}
// here some onclicks etc, other methods
#Override protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawers();
}
}
#Override public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawers();
} else {
super.onBackPressed();
}
}
#Override protected void onPause() {
super.onPause();
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawers();
}
}
}
And AbstractToolbarActivity.java:
public abstract class AbstractToolbarActivity extends AppCompatActivity {
#Bind(R.id.action_bar) Toolbar mToolbar;
#Override protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
initToolbar();
}
protected void initToolbar() {
setSupportActionBar(mToolbar);
}
}
Here is my MainActivity.java
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
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.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
ListView mNavigationDrawer;
private Toolbar mToolbar;
private ActionBarDrawerToggle mDrawerToggle;
DrawerLayout mDrawerLayout;
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
public static final String PREF_FILE_NAME = "pref";
public static final String KEY_USER_LEARNED_DRAWER = "user_learned_drawer";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
mFromSavedInstanceState = true;
}
mToolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.main_DrawerLayout);
mNavigationDrawer = (ListView) findViewById(R.id.navigation_drawer);
mNavigationDrawer.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.navigation_drawer_list)));
setDrawers(mDrawerLayout, mToolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void setDrawers(DrawerLayout drawerLayout, Toolbar toolbar) {
mDrawerLayout = drawerLayout;
mToolbar = toolbar;
mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!mUserLearnedDrawer)
mUserLearnedDrawer = true;
saveToPreference(getApplicationContext(), KEY_USER_LEARNED_DRAWER, mUserLearnedDrawer + "");
// getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
// getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (!mUserLearnedDrawer && !mFromSavedInstanceState)
mDrawerLayout.openDrawer(mNavigationDrawer);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static void saveToPreference(Context context, String preferenceName, String preferenceValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(preferenceName, preferenceValue);
editor.apply();
// editor.commit()
}
public static String readFromPreference(Context context, String preferenceName, String defaultValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(preferenceName, defaultValue);
}
}
Here is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="#+id/app_bar"
layout="#layout/app_bar" />
<android.support.v4.widget.DrawerLayout
android:name="#+id/main_DrawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="xymen.chetanbhagatnovels.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
<ListView
android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:divider="#null"/>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
It is giving me error on line mDrawerLayout.setDrawerListener(mDrawerToggle);
I dont know why. I also have another project from which I have copied all but it is nor getting error but this one does. HELP
I just ran your code and figured it out.
The problem is that you have specified name instead of id for the android.support.v4.widget.DrawerLayout.
Just change this:
android:name="#+id/main_DrawerLayout"
To this:
android:id="#+id/main_DrawerLayout"
With that change, the NullPointerException was fixed and it ran fine for me.
Based on the limited information you've provided, your mDrawerLayout member is null.
This can happen if you have multiple versions of the same layout file in different layout folders that are inconsistent with one another.
I suspect you have a layout file named main_activity.xml in your res/layout folder that has declared a DrawerLayout view with the id main_DrawerLayout, and another version of this layout file (perhaps in your res/layout-land folder) that either does not have this DrawerLayout view, or has it but declared with a different view id.
As a result findViewById(R.id.main_DrawerLayout) is returning null from one of your alternate main_activity.xml layouts and you are getting a NullPointerException as a result.
I know this is a common sort of question but I have tried most of all the solution available on net but it is still not working, so please help.
I am trying to create a navigation drawer in my project I am facing the logcat error on very first run that "android.view.InflateException: Binary XML file: Error inflating class fragment".
I have created 4 files:
the main activity
its layout
Drawer activity
its layout
The code is below:
1) the mainactivity which I have named Home
package GJ.helpinghand;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class Home extends FragmentActivity {
private ListView con;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Drawer drawer_instance = (Drawer) getFragmentManager().findFragmentById(R.id.drawer_frag);
drawer_instance.setUp(R.id.drawer_frag,(DrawerLayout) findViewById(R.id.drawer_layout));
/*Drawer_try drawer_instance = (Drawer_try) getFragmentManager().findFragmentById(R.id.drawer_frag);
drawer_instance.setUp(R.id.drawer_frag,(DrawerLayout) findViewById(R.id.drawer_layout));
*/
con = (ListView)findViewById(R.id.content);
final String[] info = new String[] { "Android List View", "Adapter implementation" };
ArrayAdapter<String> adap = new ArrayAdapter<String>(getApplicationContext(),R.layout.listlay,R.id.title, info);
con.setAdapter(adap);
con.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String to = info[position];
Toast.makeText(getApplicationContext(), to , Toast.LENGTH_LONG).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, 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);
}
}
The XML for main Activity which is causing error:
<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"
android:orientation="vertical"
tools:context="GJ.helpinghand.Home" >
<RelativeLayout
android:id="#+id/core"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView1"
android:background="#android:color/darker_gray"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="#string/file"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ListView
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/textView1"
android:divider="#android:color/holo_orange_light" />
</RelativeLayout>
<fragment
android:id="#+id/drawer_frag"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
class="com.fragment.NavigationDrawerFragment"
tools:layout="#layout/fragment_drawer" />
3) the drawer's java file:
package GJ.helpinghand;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class Drawer extends Fragment {
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private NavigationDrawerCallbacks mCallbacks;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public Drawer() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState
.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of
// actions in the action bar.
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_drawer, container, false);
mDrawerListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(getActionBar()
.getThemedContext(), android.R.layout.simple_list_item_1,
android.R.id.text1, new String[] {
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3), }));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null
&& mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout,R.drawable.ic_drawer,
R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().invalidateOptionsMenu(); // calls
// onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to
// prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true)
.commit();
}
getActivity().invalidateOptionsMenu(); // calls
// onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce
// them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException(
"Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar.
// See also
// showGlobalContextActionBar, which controls the top-left area of the
// action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT)
.show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to
* show the global app 'context', rather than just what's in the current
* screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return getActivity().getActionBar();
}
/**
* Callbacks interface that all activities using this fragment must
* implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
4) The XML for Drawer:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="GJ.helpinghand.Drawer$PlaceholderFragment" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</FrameLayout>
5) And the Manifest File:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="GJ.helpinghand"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="21" />
<permission android:name="WRRITE_EXTERNAL_STORAGE"></permission>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Splash"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Login"
android:label="#string/title_activity_login" >
</activity>
<activity
android:name=".Home"
android:label="#string/title_activity_home" >
</activity>
<activity
android:name=".Drawer"
android:label="#string/title_activity_drawer" >
</activity>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
</activity>
</application>
</manifest>
Your XML for Main Activity should be look like this
<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">
<RelativeLayout
android:id="#+id/core"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView1"
android:background="#android:color/darker_gray"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="#string/file"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ListView
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/textView1"
android:divider="#android:color/holo_orange_light" />
</RelativeLayout>
<fragment
android:id="#+id/drawer_frag"
android:name="com.fragment.NavigationDrawerFragment"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
tools:layout="#layout/fragment_drawer" />
</android.support.v4.widget.DrawerLayout>
In the fragment change class attribute to android:name as android:name="com.fragment.NavigationDrawerFragment"
Also there is a mistake in onCreateView method of Drawer because here you are inflating a layout named fragment_drawer and forcibly casting FrameLayout to a ListView which will lead to inflation error
to resolve this add a ListView in your drawer xml as given below
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="GJ.helpinghand.Drawer$PlaceholderFragment" >
<ListView
android:id="#+id/drawerList"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</FrameLayout>
Now map this ListView to your DrawerListView in code as below in onCreateView method
View drawer= inflater.inflate(
R.layout.fragment_drawer, false);
mDrawerListView = (ListView)drawer.findViewById(R.id.drawerList);
.....Your code
return drawer;
Hope this will help you, if you find this helpful please mark it as answer.
All the Best!!!
I'm trying to add a Navigation Drawer to my app but I'm getting an error:
Caused by: java.lang.NullPointerException
at com.conversions.rolando.conversions.MainActivity.onCreate(MainActivity.java:66)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
The error points to:
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer,(DrawerLayout)findViewById(R.id.drawer_layout));
Which is part of the MainActivity.java:
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.text.DecimalFormat;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayShowHomeEnabled(true);
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer,(DrawerLayout)findViewById(R.id.drawer_layout));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is the NavigationDrawerFragment.java where setUp() is located.
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
activity_main.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:layout_weight="1"
android:background="#drawable/my_rect"
android:elevation="2dp">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center"
android:layout_weight="0.5">
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="#color/secondary_text"
android:text="#string/unit_from"
android:layout_weight="1.10"
android:id="#+id/from" />
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="#color/secondary_text"
android:text="#string/conversion_from"
android:fontFamily="sans-serif-light"
android:id="#+id/conv_from"
android:textSize="25sp"
android:layout_weight="1"
android:clickable="true" />
<View style="#style/Divider"
android:paddingTop="3dp"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="#color/secondary_text"
android:text="#string/unit_to"
android:id="#+id/to"
android:layout_weight="1"
android:paddingTop="10dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="#string/conversion_to"
android:fontFamily="sans-serif-light"
android:textColor="#color/primary_text"
android:id="#+id/conv_to"
android:layout_weight="1"
android:textSize="30sp" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:layout_weight="1.5"
android:gravity="center"
android:paddingBottom="12dp">
<ImageButton
android:id="#+id/fab_image_button"
android:layout_width="#dimen/fab_button_diameter"
android:layout_height="#dimen/fab_button_diameter"
android:background="#drawable/circle"
android:tint="#android:color/white"
android:src="#drawable/ic_cached_white_24dp"
android:scaleType="center" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_weight="0.55"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="#layout/num_pad" />
</LinearLayout>
</LinearLayout>
<!-- The navigation drawer -->
<fragment
android:id="#+id/fragment_navigation_drawer"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity = "start"
app:layout="#layout/fragment_navigation_drawer"
android:name="com.conversions.rolando.conversions.NavigationDrawerFragment"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
I'm not sure what I'm missing and whether the problem is on the MainActivity.java or the NavigationDrawerFragment.java.
Thanks!