I'm struggling with the toolbar and drawer. I'm trying to make the burger switch to arrow when I'm adding a new fragment to the backstack but there is no way to do it.
Maybe I'm missing something but I could not find a way. Anyone had the same problem?
This is the declaration:
mDrawerToggle = new ActionBarDrawerToggle(
getActivityCompat(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
((BaseActivity) getActivityCompat()).getToolbar(),
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
)
This is the function I call when a fragment is added to the back stack
public void setToggleState(boolean isEnabled) {
if (mDrawerLayout == null)
return;
if (isEnabled) {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
mDrawerToggle.onDrawerStateChanged(DrawerLayout.LOCK_MODE_UNLOCKED);
} else {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
mDrawerToggle.onDrawerStateChanged(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}
mDrawerToggle.syncState();
}
I think all you have to do is to delete the third argument. Thus:
mDrawerToggle = new ActionBarDrawerToggle(
getActivityCompat(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
// ((BaseActivity) getActivityCompat()).getToolbar(), <== delete this argument
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
);
May it helps.
I had the same problem. My solution was this:
Make sure your activity implements onBackStackChangedListener. In your activities' onCreate I set the backstack listener and I set up the toolbar
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFm = getFragmentManager();
mFm.addOnBackStackChangedListener(this);
// Setup toolbar
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setVisibility(View.VISIBLE);
setSupportActionBar(mToolbar);
// Setup drawer toggle
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.menu_open, R.string.menu_close);
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle.syncState();
// Setup initial fragment
if (savedInstanceState == null) {
mCurrentFragment = DashboardFragment.newInstance();
mFm.beginTransaction().add(CONTAINER_ID, mCurrentFragment).commit();
}
}
Also remember to set:
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
Now the magic happens in onBackStackChanged(). Setting the setDrawerIndicatorEnabled to true for the top-most fragment and setDisplayHomeAsUpEnabled as false for that fragment. Inverse for the other ones. I also had to call syncState or else the hamburger wouldn't reappear:
#Override
public void onBackStackChanged() {
mDrawerToggle.setDrawerIndicatorEnabled(mFm.getBackStackEntryCount() == 0);
getSupportActionBar().setDisplayHomeAsUpEnabled(mFm.getBackStackEntryCount() > 0);
mDrawerToggle.syncState();
}
I have achieved it using following layout:
i have used ActionBarDrawerToggle v7
Drawer.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.toolbar.Drawer" >
<include
android:id="#+id/tool1"
layout="#layout/toolbar" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/tool1" >
<FrameLayout
android:id="#+id/mainContent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<!-- Nav drawer -->
<ListView
android:id="#+id/drawerList"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:background="#android:color/white"
android:divider="#android:color/white"
android:dividerHeight="8dp"
android:drawSelectorOnTop="true"
android:headerDividersEnabled="true" />
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app1="http://schemas.android.com/apk/res/com.example.toolbar"
android:id="#+id/my_awesome_toolbar"
android:layout_width="fill_parent"
android:layout_height="75dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app1:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app1:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" >
</android.support.v7.widget.Toolbar>
Drawer.java
package com.example.toolbar;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
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.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Drawer extends ActionBarActivity {
ActionBarDrawerToggle mDrawerToggle;
private String[] days;
ArrayAdapter<String> adapter;
private ListView mDrawerList;
DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer);
days = new String[] { "sunday", "monday", "tuesday", "wednesday",
"thursday", "friday", "saturday" };
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, days);
mDrawerList = (ListView) findViewById(R.id.drawerList);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Fragment fragment = new MyFragment();
Bundle args = new Bundle();
args.putString(MyFragment.ARG_PLANET_NUMBER, days[position]);
// args.putInt(MyFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.mainContent, fragment).commit();
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.tool1);
setSupportActionBar(toolbar);
toolbar.setTitle("ToolBar Demo");
toolbar.setLogo(R.drawable.ic_launcher);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar,
R.string.open_navigation_drawer,
R.string.close_navigation_drawer) {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
// TODO Auto-generated method stub
super.onDrawerSlide(drawerView, slideOffset);
}
/** Called when a drawer has settled in a completely closed state. */
#Override
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle("hello");
}
/** Called when a drawer has settled in a completely open state. */
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("hi");
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true); //<---- added
// getSupportActionBar().setHomeButtonEnabled(true); //<---- added
}
#Override
public boolean onOptionsItemSelected(MenuItem item) { // <---- added
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) { // <---- added
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState(); // important statetment for drawer to
// identify
// its state
}
#Override
public void onConfigurationChanged(Configuration newConfig) { // <---- added
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(Gravity.START | Gravity.LEFT)) { // <----
// added
mDrawerLayout.closeDrawers();
return;
}
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
#hata's answer is spot-on for most cases.
But actually, you were not wrong using toolbar as argument to the ActionBarDrawerToggle(...) constructor.
Of course, there's no sense in doing that if you're using the stock Toolbar AppCompatActivity provides by using, say the stock Theme.AppCompat.Light root theme.
Even if you want a custom Toolbar in your layout, e.g. if you're implementing the Material Design's over-toolbar-under-statusbar Navigation Drawer pattern, you can still call setSupportActionBar(toolbar) and still not pass the toolbar to ActionBarDrawerToggle() letting the activity handle the navigation icon.
But if you really want to bind your ActionBarDrawerToggle to a Toolbar that's not activity's action bar, and maybe has different styling and a different icon or whatever -- there's still a way to go.
The thing is, when you don't pass the toolbar as the fourth parameter, the activity is supposed to provide the navigation icon (the arrow) -- and AppCompatActivity returns the value of homeAsUpIndicator attribute -- it's defined in either of the standard AppCompat themes.
However, when you explicitly pass the Toolbar, ActionBarDrawerToggle expects the toolbar instance to provide the navigation indicator drawable -- and it doesn't, because even if you apply the appropriate style to it like this:
<android.support.v7.widget.Toolbar
...
app:theme="?actionBarTheme"
style="#style/Widget.AppCompat.Toolbar">
for some reason (maybe it's even a bug), the Widget.AppCompat.Toolbar style doesn't have navigationIcon attribute, so Toolbar returns null when ActionBarDrawerToggle asks it for the nav icon. So, to cope with this, you simply derive from the style and add the attribute:
<android.support.v7.widget.Toolbar
...
app:theme="?actionBarTheme"
style="#style/MyWidget.Toolbar">
<!-- styles.xml -->
<style name="MyWidget.Toolbar" parent="Widget.AppCompat.Toolbar">
<item name="navigationIcon">?homeAsUpIndicator</item>
</style>
Now you can use the toolbar-aware constructor ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, 0, 0) and still have the navigation icon in place.
this line makes sure hamburger icon is changed to arrow on clicking. Make sure you have this written in your code.
mDrawerLayout.setDrawerListener(mDrawerToggle);
Related
I have created a navigation drawer and now i want to use it in all my activity can anyone tell me how it is done ? i have gone through various ansers but it didn't help I have created a navigation drawer and now i want to use it in all my activity can anyone tell me how it is done ? i have gone through various ansers but it didn't help
here is my code:
public class AbstractActivity extends AppCompatActivity {
private String[] mPlanetTitles;
private LinearLayout mDrawerList;
protected DrawerLayout mDrawerLayout;
protected ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
protected Toolbar toolbar;
protected FrameLayout framelayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_abstract);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (LinearLayout) findViewById(R.id.left_drawer);
framelayout = (FrameLayout)findViewById(R.id.content_frame);
mTitle = mDrawerTitle = getTitle().toString();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
toolbar, R.string.drawer_open, R.string.drawer_close){
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_Aboutus).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
private void selectItem(int position) {
switch(position) {
case 1:
Intent a = new Intent(this, Welcome.class);
startActivity(a);
break;
case 2:
Intent b = new Intent(this, Welcome.class);
startActivity(b);
break;
default:
}
}
public boolean onOptionsItemSelected(MenuItem item){
int items = item.getItemId();
switch(items){
case R.id.action_Settings:{
Intent intent = new Intent(this,Settings.class);
startActivity(intent);
}break;
case R.id.action_Contact_us:{
Intent intent = new Intent(this,Contact.class);
startActivity(intent);
}break;
case R.id.action_Aboutus:{
Intent intent = new Intent(this,ChartStyle.class);
startActivity(intent);
}break;
case R.id.action_Profile:{
Intent intent = new Intent(this,ChartStyle.class);
startActivity(intent);
}break;
}
return super.onOptionsItemSelected(item);
}
}
<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">
<include layout="#layout/toolbar"/>
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<LinearLayout android:id="#+id/left_drawer"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:orientation="vertical"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#0F6177">
<LinearLayout android:id="#+id/view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<include layout="#layout/navigation_drawer"></include>
</LinearLayout>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
I implimented this code but it isnt working
package com.astro.famouspandit.Activities.Abstract;
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.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import com.astro.famouspandit.R;
public abstract class NavigationActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setTitle("Title");
}
}
/**
* This method overrides the setContentView method to set DrawerLayout as a main layout.
*
* #param layoutResID Layout, which will be set in DrawerLayout as a content frame
*/
#Override
public void setContentView(final int layoutResID) {
super.setContentView(R.layout.activity_navigation);
final ViewStub content =(ViewStub)findViewById(R.id.content_frame);
content.setLayoutResource(layoutResID);
content.inflate();
initDrawer();
}
/**
* This method initializes DrawerLayout and DrawerToggle
*/
private void initDrawer() {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.setDrawerShadow(R.drawable.ic_drawer_button, GravityCompat.START);
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
null,
R.string.drawer_open,
R.string.drawer_close
) {
public void onDrawerClosed(final View view) {
//invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(final View drawerView) {
//invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(final Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(final Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(final MenuItem item) {
return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
/**
* This method is called when user presses the back button. If the drawer is opened, it will be closed.
* Otherwise will be called the parent implementation.
*/
#Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawers();
} else {
super.onBackPressed();
}
}
}
activity_navigation.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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ViewStub
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<RelativeLayout
android:id="#+id/drawer_container"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:clickable="true"
android:background="#android:color/white"
android:layout_gravity="start">
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
in this class i am extending it:
public class Contact extends NavigationActivity implements View.OnClickListener {
private EditText mName,mNumber,mEmail,mMessage;
private FancyButton mSbmt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact);
So, first of all you have to create a base abstract Activity with DrawerLayout:
public abstract class NavigationActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setTitle("Title");
}
}
/**
* This method overrides the setContentView method to set DrawerLayout as a main layout.
*
* #param layoutResID Layout, which will be set in DrawerLayout as a content frame
*/
#Override
public void setContentView(final int layoutResID) {
super.setContentView(R.layout.navigation_drawer);
final ViewStub content = (ViewStub) findViewById(R.id.content_frame);
content.setLayoutResource(layoutResID);
content.inflate();
initDrawer();
}
/**
* This method initializes DrawerLayout and DrawerToggle
*/
private void initDrawer() {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
null,
R.string.drawer_open,
R.string.drawer_close
) {
public void onDrawerClosed(final View view) {
//invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(final View drawerView) {
//invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(final Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(final Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(final MenuItem item) {
return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
/**
* This method is called when user presses the back button. If the drawer is opened, it will be closed.
* Otherwise will be called the parent implementation.
*/
#Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawers();
} else {
super.onBackPressed();
}
}
}
Which uses a layout navigation_drawer.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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ViewStub
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<RelativeLayout
android:id="#+id/drawer_container"
android:layout_width="#dimen/drawer_width"
android:layout_height="match_parent"
android:orientation="vertical"
android:clickable="true"
android:background="#color/gray_dark"
android:layout_gravity="start">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="This is drawer"/>
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
After that you can simply create some Activity and set its layout into ViewStub with id "content_frame". It will be done automatically in setContentView method in NavigationActivity
public class MainActivity extends NavigationActivity {
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
You also have to use a theme with ActionBar:
<resources
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
<item name="actionBarStyle">#style/MyActionBar</item>
</style>
<style name="MyActionBar" parent="#style/Widget.AppCompat.Light.ActionBar.Solid">
<item name="background">#android:color/white</item>
<item name="android:background" tools:ignore="NewApi">#android:color/white</item>
</style>
</resources>
And set it in your manifest file:
<application
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
...
I am implementing navigation drawer in my android app. But problem is two icons appear on actionbar. I have added ActionBarDrawerToggle and it seems second icon is displayed from ActionBarDrawerToggle. Please tell me where is the error in my code.
Please tell me wheat could be error.
And Here is complete code
package com.example.newdrawer;
import android.os.Bundle;
import android.app.Activity;
import android.content.res.Configuration;
import android.support.v4.app.ActionBarDrawerToggle;
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 MainActivity extends Activity {
DrawerLayout mDrawerLayout;
ActionBarDrawerToggle mActionBarDrawerToggle;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getActionBar().setIcon(R.drawable.ic_launcher);
String[] listItems = {"first", "second", "third"};
listView = (ListView) findViewById(R.id.drawer);
listView.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.textView1, listItems));
listView.setOnItemClickListener(new DrawerItemClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mActionBarDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_launcher, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_opened, /* "open drawer" description */
R.string.drawer_closed /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle("appname");
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle("select item");
}
};
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
// to change up caret
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mActionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mActionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
// navigation drawer click listener
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "You clicked:"+String.valueOf(position), Toast.LENGTH_LONG).show();
mDrawerLayout.closeDrawers();
}
}
}
Here is my 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=".MainActivity" >
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width = "match_parent"
android:layout_height= "match_parent"
android:id = "#+id/text1"
android:text = "Hello World"/>
<ListView
android:id="#+id/drawer"
android:layout_width = "210dp"
android:layout_height = "match_parent"
android:layout_gravity = "start"
android:background="#android:color/white"/>
</android.support.v4.widget.DrawerLayout>"
</LinearLayout>
Thank you in advance
the first icon is supposed to be drawer icon (aka hamburger). but you replaced it with launcher icon
mActionBarDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.R.drawable.ic_launcher, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_opened, /* "open drawer" description */
R.string.drawer_closed /* "close drawer" description */
)
replace R.drawable.ic_launcher with actual drawer icon resource in code above.
I've been at this for hours and can't seem to get the drawer to show up at all. Here is my code maybe someone can tell me what is wrong here... The app runs with no errors until I get to the activity with the Drawer then it crashes.
Here is my code:
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.support.v7.app.ActionBarDrawerToggle;
public class FlavorListView extends ActionBarActivity {
//shared preference
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
#Override
public boolean onCreateOptionsMenu(Menu action_setting) {
//MenuInflater inflater = getMenuInflater();
//inflater.inflate(R.menu.menu_welcome,action_setting);
//drawer
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.navigation_drawer);
mDrawerToggle = new ActionBarDrawerToggle(FlavorListView.this, mDrawerLayout,
R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
return true;
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
//boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
//menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
//return super.onPrepareOptionsMenu(menu);
//drawer end
return true;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_flavor);
String[] select_flavor_list = {"Kansas City", "Memphis", "Texas", "North Carolina", "South Carolina","Alabama"};
ListAdapter FlavorListAdapter = new ArrayAdapter<String>(this, R.layout.row_layout_flavor, R.id.flavor_text_view,
select_flavor_list);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(FlavorListAdapter);
//For list view selection, begin here...
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//String flavorPicked = String.valueOf(parent.getItemAtPosition(position));
FoodStyleDialog cdd = new FoodStyleDialog(FlavorListView.this);
cdd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
cdd.show();
return true;
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View v, int position, long id) {
//GlobalClass flavorPref = ((GlobalClass)getApplicationContext());
String flavorPicked = String.valueOf(adapterView.getItemAtPosition(position));
if (flavorPicked.equals("Kansas City")) {
Intent intent = new Intent(FlavorListView.this, KansasCity.class);
startActivity(intent);
setContentView(R.layout.kansas_city);
Toast.makeText(FlavorListView.this, "Looks like " + flavorPicked +
" style be your flavor! You can change your flavor anytime in the settings menu.",
Toast.LENGTH_LONG).show();
}
else if (flavorPicked.equals("Memphis")) {
Intent intent = new Intent(FlavorListView.this, KansasCity.class);
startActivity(intent);
setContentView(R.layout.kansas_city);
Toast.makeText(FlavorListView.this, "Looks like " + flavorPicked +
" style be your flavor! You can change your flavor anytime in the settings menu.",
Toast.LENGTH_LONG).show();
}
}
});
}
}
I'm getting a java.lang.NullPointerException and the debugger is saying at (FlavorListView.java:57) which is at mDrawerLayout.setDrawerListener(mDrawerToggle);
IF I comment this line out the app runs but no drawer...
please help. thanks :)
Drawer Layout 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/navigation_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
The drawer is given a fixed width in dp and extends the full height of
the container. A solid background is used for contrast
with the content view. -->
<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="#ffff"/>
</android.support.v4.widget.DrawerLayout>
FlavorListView Acivity xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingBottom="16dp"
android:paddingTop="16dp"
tools:context=".FlavorListView"
>
<TextView
android:layout_width="match_parent"
android:layout_height="40dp"
android:text="Choose Your Flavor"
android:textAlignment="center"
android:textSize="30sp"
android:textStyle="bold"
android:gravity="center_horizontal"
/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:listSelector="#drawable/abc_list_pressed_holo_light" />
</LinearLayout>
If you're getting an NPE there, then mDrawerLayout must be null. Make sure drawer_layout is the right ID to find the drawer in your XML. You need to inflate the Drawer Layout XML file too. You almost have it right (you need to replace menu_welcome below with the name of your file):
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_welcome, action_setting);
mDrawerLayout = (DrawerLayout) action_setting.findViewById(R.id.navigation_drawer);
Place below code in your onCreate and NOT in
onCreateOptionMenu
/------------------------------------------------------------/
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.navigation_drawer);
mDrawerToggle = new ActionBarDrawerToggle(FlavorListView.this, mDrawerLayout,R.drawable.ic_menu,
R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
Read the example codes carefully before using it
Im working on a new app with Navigation Drawer (Using Android template). But I want replace the default listview with another views.
SOLVED:
I have to edit my .java code to modify the createView method to match with my layout. Thanks for all
QUESTION:
My class extends from ActionBarActivity and implements NavigationDrawerFragment.NavigationDrawerCallbacks
I want make some like this:
---------
EDITTEXT
--------- (separator)
(ListView with Links)
Link 1
Link 2
--------(separator)
(ListView with Links)
Link 1
Link 2
...
..
.
Ok, I was trying with this:
activity_mail.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.myapp" >
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<fragment
android:id="#+id/navigation_drawer"
android:name="com.extasis.musichunter.NavigationDrawerFragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start" />
</android.support.v4.widget.DrawerLayout>
fragment_navigation_drawer.xml (not working version)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/buscador"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text" >
<requestFocus />
</EditText>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#cccc"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
tools:context="com.example.myapp" />
</LinearLayout>
fragment_navigation_drawer.xml (working version)
<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:background="#cccc"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
tools:context="com.extasis.musichunter.NavigationDrawerFragment" />
NavigationDrawerFragment.java
package com.extasis.musichunter;
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<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);
}
/**
* 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).commit();
}
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);
}
}
This is the error that I get:
07-14 18:00:02.971: E/AndroidRuntime(20518): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapp/com.example.myapp.MainActivity}: android.view.InflateException: Binary XML file line #31: Error inflating class fragment
I suppose that I have to modify the NavigationDrawerFragment class but I dont know that elements I have to change, add or remove. Can anybody help me with this?
Edit:
After chatting with you we saw that your NavigationDrawerClass expects a ListView in this mthod:
#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<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;
}
In this function the View is created and build of the various layout items. You would have to change the code so that the fragment not only build a listview, instead you would have to manually build the menu-file and when create the view inflate that xml file instead of only a List.
Sorry to not provide code atm, the time is running a bit low :-)
Old answer from me, before edit:
I think your missing different points in your app/project. I see that you still have lines like this
tools:context="com.example.myapp"
in your files. Since you said youre using a template you have to adjust this to your own apps name etc. Not sure you did that, i cannot see it from provided code.
But what i see is that in another line there is:
android:name="com.extasis.musichunter.NavigationDrawerFragment"
So one the 2 is not right i guess.
You should re-check App fundamentals on the Tutorial Pages on developer Section on Android.
Otherwise your code is not that wrong, you can simply put anything at the menu, like this
<?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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView2" />
</LinearLayout>
1.make sure yourActivity is extending android.support.v4.widget.DrawerLayout
2.inflate exception is just a handler for another problem.
the issue is out of memory exception.
3.add the android supportv4.jar
I'm trying to follow this tutorial on how to create a Navigation Drawer, but I don't want to use Fragments to show new content after the user select an item from the drawer list. What's the best aproach to get around this problem?
I'm using API 10 which doesn't implements Fragments.
First, API 10 has access to fragments via the same Android Support package that contains the DrawerLayout. This has been around for over two years, and you should not be trying to mess with new things like DrawerLayout if you are unfamiliar with what Android has had for the past two years.
Second, there is nothing with DrawerLayout that is tied to fragments. Quoting the Web page that you linked to:
When the user selects an item in the drawer's list, the system calls onItemClick() on the OnItemClickListener given to setOnItemClickListener(). What you do in the onItemClick() method depends on how you've implemented your app structure.
If you read those two sentences closely, you will see that the word "fragment" appears in neither of them. That is because DrawerLayout is not tied to fragments. The sample code they show uses fragments, but that is merely sample code.
Hence, you are welcome to update your UI however you want:
execute a FragmentTransaction using the Android Support package's backport of fragments, or
start an activity, or
call setContentView() again on your existing activity, or
otherwise modify the UI of the existing activity (e.g., hide/show some widgets)
You may use also LayoutInflater class.
Create xml layout file.
Find the View to change using findViewById.
Remove all children from the found View using .removeAllViews() method.
Inflate xml layout content into found View using .inflate() method.
This is an example:
LinearLayout layoutToChange = (LinearLayout)findViewById(R.id.layout_to_change);
layoutToChange.removeAllViews();
LayoutInflater inflater = LayoutInflater.from(this);
LinearLayout newLayout = (LinearLayout)inflater.inflate(R.layout.new_layout, null);
layoutToChange.addView(newLayout);
basic drawer without fragment
package xxxxxx;
import android.content.res.Configuration;
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.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 loginhome extends AppCompatActivity {
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginhome);
Toolbar topToolBar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(topToolBar);
mDrawerList = (ListView)findViewById(R.id.navList);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void addDrawerItems() {
String[] osArray = { "Android", "iOS", "Windows", "OS X", "Linux" };
mAdapter = new ArrayAdapter<String>(this, R.layout.drawer_items,R.id.label ,osArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(loginhome.this, "Time for an upgrade!", Toast.LENGTH_SHORT).show();
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, 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("Navigation!");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#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 onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, 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_help) {
Toast.makeText(loginhome.this, "setting", Toast.LENGTH_LONG).show();
}
if(id == R.id.action_place){
Toast.makeText(loginhome.this, "Refresh App", Toast.LENGTH_LONG).show();
}
if(id == R.id.action_search){
Toast.makeText(loginhome.this, "Create Text", Toast.LENGTH_LONG).show();
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
draweritems.xml
<?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">
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000"
android:textSize="30sp"
android:background="#D3D3D3">
</TextView>
</LinearLayout>
toolbar.xml
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:elevation="4dp"
android:id="#+id/toolbar"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
>
</android.support.v7.widget.Toolbar>
use this code
private void selectItem(int position) {
// Locate Position
switch (position) {
case 0:
startActivity(new Intent(this,TEST.class));
break;