I am implementing a very simple example of NavigationDrawer. The example works fine, but I have a strange problem. The icon for NavigationDrawer (generally ic_drawer) does not show up in the ActionBar. I have tried using different icon images, but didn't achieved the desired result. Here's the code. The project has only one activity named MainActivity.java.
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mListView;
private ActionBarDrawerToggle mDrawerToggle;
private String[] array = new String[] { "Hello", "hola", "namaste",
"salaam" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
mListView = (ListView) findViewById(R.id.list);
getActionBar().setDisplayHomeAsUpEnabled(true);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getApplicationContext(),
android.R.layout.simple_dropdown_item_1line, array);
mListView.setAdapter(adapter);
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getApplicationContext(), array[arg2],
Toast.LENGTH_SHORT).show();
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.open, R.string.close) {
#Override
public void onDrawerClosed(View drawerView) {
// TODO Auto-generated method stub
invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if (mDrawerToggle.onOptionsItemSelected(item))
return true;
return super.onOptionsItemSelected(item);
}
}
And if I comment out the line with code getActionBar().setDisplayHomeAsUpEnabled(true);, the code stops working, meaning NavigationDrawer does not open.
For reference, the xml layout for this activity is:
activity_main.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="change aaaega, hum laaenge" />
<ListView
android:id="#+id/list"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice" />
</android.support.v4.widget.DrawerLayout>
Any suggestions ?
Thanks.
Include this part of code in your program,
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// call mDrawerToggle.onOptionsItemSelected(), if it returns true
// then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
Related
Hiho!
I build a navigation drawer into my android app. I used the howto from http://blog.teamtreehouse.com/add-navigation-drawer-android and modified it at one place of the layout. I can activate the menu when i touch and swing my finger from left to right. But if I touch the hamburger menu nothing hapend. What ist wrong?
If i swipped in the menu the icon changed to an arrow, so there is a connection.
Hope some one can help me.
My Java Class (Main Activity):
public class AmericanFootball extends AppCompatActivity {
private MenuItem mi;
public static Context context;
private ListView mDrawerList;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private String mActivityTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = (Context) this;
setContentView(R.layout.activity_american_football);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(getText(R.string.app_name));
setSupportActionBar(toolbar);
mDrawerList = (ListView)findViewById(R.id.navList);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawerLayout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
checkInternet ci = new checkInternet();
boolean internet=ci.isNetzwerkVerfuegbar((Context) this);
TextView tv = (TextView) findViewById(R.id.tv_hello);
tv.setTypeface(FontManager.getTypeface((Context) this, FontManager.FONTAWESOME));
tv.setText(R.string.fa_icon_areachart);
tv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimaryLight));
}
#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_american_football, menu);
MenuItem mi = menu.findItem(R.id.action_refresh);
TextDrawable td = new TextDrawable((Context) this);
td.setText(getString(R.string.fa_refresh));
td.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimaryLight));
td.setTextSize(30);
mi.setIcon(td);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ImageView iv = (ImageView)inflater.inflate(R.layout.iv_refresh, null);
iv.setImageDrawable(td);
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;
}
if (id == R.id.action_refresh) {
doRefreshGames(item);
}
return super.onOptionsItemSelected(item);
}
#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);
}
private void addDrawerItems() {
String[] osArray = { "Android", "iOS", "Windows", "OS X", "Linux" };
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(AmericanFootball.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);
}
}
My layoutfile:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="k0f.de.americanfootball.AmericanFootball">
<android.support.design.widget.AppBarLayout
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:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_american_football" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<ListView
android:id="#+id/navList"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="left|start"
android:background="#ffeeeeee"/>
</android.support.v4.widget.DrawerLayout>
</android.support.design.widget.CoordinatorLayout>
I found my mistake. Forgot a little thing:
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
}
I am developing a quiz app which consists of drawer layout in all the activities.The contents in the drawer is same and i want it in all the activities.By searching google i found a solution that declaring drawer in one activity and inherit in all the activities,it works well too.I am attaching the code below.
Now the problem is that i need Tab in one of by activity so i don't know how to inherit 2 activity in here[which is not possible].
Can any one help me out with this problem?
Simply saying,
I have a option that i can extend only i class what to do if i want two classes?
DrawActivity.java
public void onCreateDrawer() {
// R.id.drawer_layout should be in every activity with exactly the same id.
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle(DrawActivity.this,drawerLayout,R.drawable.ic_drawer2,R.string.app_name,R.string.app_name)
{
public void onDrawerClosed(View view)
{
getActionBar().setTitle(R.string.app_name);
}
public void onDrawerOpened(View drawerView)
{
getActionBar().setTitle(R.string.app_name);
}
};
drawerLayout.setDrawerListener(drawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
//getActionBar().setBackgroundDrawable(new ColorDrawable(Color.RED));
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getString("logged","").toString().equals("logged")) {
layers = getResources().getStringArray(R.array.layers_array1);
flag=0;
}
else {
layers = getResources().getStringArray(R.array.layers_array);
flag=1;
}
drawerList = (ListView) findViewById(R.id.left_drawer);
drawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,layers));
drawerList.setSelector(R.color.darkgreen);
drawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
selectItemFromDrawer(pos);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
I've implemented ActionBarDrawerToggle for NavigationDrawer and also used ActionBar.
How can I handle both click events because both require onOptionsItemSelected(MenuItem item) method?
Is there any other way around?
public class A1 extends AppCompatActivity implements OnItemClickListener {
String[] menu;
DrawerLayout dLayout;
ListView dList;
ArrayAdapter < String > adapter;
ActionBarDrawerToggle drawListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a1);
menu = new String[] {
"Home", "Android", "Windows", "Linux", "Raspberry Pi", "WordPress", "Videos", "Contact Us"
};
dLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
dList = (ListView) findViewById(R.id.left_drawer);
adapter = new ArrayAdapter < String > (this, android.R.layout.simple_list_item_1, menu);
dList.setAdapter(adapter);
dList.setOnItemClickListener(this);
dList.setSelector(android.R.color.holo_blue_dark);
drawListener = new ActionBarDrawerToggle(this, dLayout, R.drawable.ic_draw, R.string.dopen) {
#Override
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Menu");
}
#Override
public void onDrawerClosed(View drawerView) {
// TODO Auto-generated method stub
super.onDrawerClosed(drawerView);
}
};
dLayout.setDrawerListener(drawListener);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public boolean onCreateOptionsMenu(Menu menu) //for actionbar
{
getMenuInflater().inflate(R.menu.actionbar, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.copy:
return showToast("Copy");
default:
return false;
}
// if(drawListener.onOptionsItemSelected(item))
// {
// return true;
// }
// return super.onOptionsItemSelected(item);
}
public boolean showToast(String message) {
Toast.makeText(getBaseContext(), message, Toast.LENGTH_SHORT).show();
return true;
}
#Override
public void onConfigurationChanged(android.content.res.Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawListener.onConfigurationChanged(newConfig);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawListener.syncState();
}
#Override
public void onItemClick(AdapterView <? > arg0, View v, int position, long id) {
selectitem(position);
dLayout.closeDrawers();
Bundle args = new Bundle();
args.putString("Menu", menu[position]);
Fragment detail = new DetailFragment();
detail.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, detail).commit();
}
public void selectitem(int position) {
dList.setItemChecked(position, true);
setTitle(menu[position]);
}
public void setTitle(String title) {
getSupportActionBar().setTitle(title);
}
}
I see you're using the latest AppCompat and stuff. Then why complicate the drawer?
Please go through this. You can make a drawer VERY quickly and easily, handle its open and close quite neatly. You don't even need the ActionBarDrawerToggle.
Cheers.
At the moment I have a Base Activity class which implements an action bar across all my activities, I now want to add to this base class so that it implements a navigation drawer. But having a base activity which implements a navigation drawer gives me a lot of conflicting view errors.
My main goal is to have a viewpager activity extend this base activity which implements a navigation drawer, How can I do this? or is there a work around?
Thanks
This is how I am doing this. I don't exactly remember where I took it but it is also changed. In my case I defined it as abstract and extended my MainActivity from this. The reason was to keep the logic related to DrawerActivity in one class so it is not mixed with my business logic.
public abstract class DrawerActivity extends BaseActivity {
private ActionBarDrawerToggle mDrawerListener;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ListAdapter mDrawerListAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_activity);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
}
#Override
public void onSupportContentChanged() {
super.onSupportContentChanged();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
if (mDrawerLayout == null) {
throw new RuntimeException(
"Your layout must be a DrawerLayout"
);
}
mDrawerList = (ListView) findViewById(R.id.drawer_list);
if (mDrawerList == null) {
throw new RuntimeException(
"Your content must have a ListView"
);
}
mDrawerListener = new ActionBarDrawerToggle(this, mDrawerLayout,
R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
onDrawerClose(view);
}
public void onDrawerOpened(View drawerView) {
onDrawerOpen(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerListener);
mDrawerList.setOnItemClickListener(mOnClickListener);
mDrawerList.setAdapter(mDrawerListAdapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerListener.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerListener.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerListener.onConfigurationChanged(newConfig);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
ensureDrawerList();
super.onRestoreInstanceState(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setContentView(int layoutResID) {
setContentView(getLayoutInflater().inflate(layoutResID, null));
}
#SuppressLint("InflateParams")
#Override
public void setContentView(View view) {
mDrawerLayout = (DrawerLayout) getLayoutInflater().inflate(
R.layout.drawer_activity, null);
FrameLayout layout = (FrameLayout) mDrawerLayout
.findViewById(R.id.content_frame);
layout.addView(view);
super.setContentView(mDrawerLayout);
}
public void onDrawerToggle() {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
public void setDrawerListAdapter(ListAdapter adapter) {
synchronized (this) {
ensureDrawerList();
mDrawerListAdapter = adapter;
}
}
public void setDrawerListSelection(int position) {
mDrawerList.setSelection(position);
mDrawerList.setItemChecked(position, true);
}
public int getSelectedDrawerItemPosition() {
return mDrawerList.getSelectedItemPosition();
}
public long getSelectedDrawerItemId() {
return mDrawerList.getSelectedItemId();
}
protected void onListItemClick(ListView l, View v, int position, long id) {
mDrawerList.setItemChecked(position, true);
mDrawerLayout.closeDrawer(mDrawerList);
}
protected void onDrawerClose(View view) {
supportInvalidateOptionsMenu();
}
protected void onDrawerOpen(View drawerView) {
supportInvalidateOptionsMenu();
}
private AdapterView.OnItemClickListener mOnClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
onListItemClick((ListView) parent, v, position, id);
}
};
public boolean isDrawerOpen() {
return mDrawerLayout.isDrawerOpen(mDrawerList);
}
private void ensureDrawerList() {
if (mDrawerList != null) {
return;
}
mDrawerList = (ListView) findViewById(R.id.drawer_list);
}
public ListView getDrawerList() {
return mDrawerList;
}
}
drawer_activity.xml:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</FrameLayout>
<!-- The navigation drawer -->
<ListView
android:id="#+id/drawer_list"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice" />
</android.support.v4.widget.DrawerLayout>
I was having the same issue and i just fixed it tonight.
I had a view pager/swipe tab setup that i wanted to add a navigation drawer to.
I built my navigation drawer to extend to my view pager according to this tutorial.
when i tried to extend it to my viewpager class i had to remove the "fragmentactivity" extend for "navigator". this gave me the same issue your having now. it took me 3 hours of research to realize that if i extend class A in class B, then as long as class A is "Extending" the same "supporting Class" that Class B needs, then you wont have that null pointer issue.
here the code: navigation_draw.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
android java:
package com.navigation.drawer.activity;
/**
* #author dipenp
*
* This activity will add Navigation Drawer for our application and all the code related to navigation drawer.
* We are going to extend all our other activites from this BaseActivity so that every activity will have Navigation Drawer in it.
* This activity layout contain one frame layout in which we will add our child activity layout.
*/
public class BaseActivity extends Activity {
/**
* Frame layout: Which is going to be used as parent layout for child activity layout.
* This layout is protected so that child activity can access this
* */
protected FrameLayout frameLayout;
/**
* ListView to add navigation drawer item in it.
* We have made it protected to access it in child class. We will just use it in child class to make item selected according to activity opened.
*/
protected ListView mDrawerList;
/**
* List item array for navigation drawer items.
* */
protected String[] listArray = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
/**
* Static variable for selected item position. Which can be used in child activity to know which item is selected from the list.
* */
protected static int position;
/**
* This flag is used just to check that launcher activity is called first time
* so that we can open appropriate Activity on launch and make list item position selected accordingly.
* */
private static boolean isLaunch = true;
/**
* Base layout node of this Activity.
* */
private DrawerLayout mDrawerLayout;
/**
* Drawer listner class for drawer open, close etc.
*/
private ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_drawer_base_layout);
frameLayout = (FrameLayout)findViewById(R.id.content_frame);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// 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
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, listArray));
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
openActivity(position);
}
});
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions between the sliding drawer and the action bar app icon
actionBarDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_launcher, /* nav drawer image to replace 'Up' caret */
R.string.open_drawer, /* "open drawer" description for accessibility */
R.string.close_drawer) /* "close drawer" description for accessibility */
{
#Override
public void onDrawerClosed(View drawerView) {
getActionBar().setTitle(listArray[position]);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(getString(R.string.app_name));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
}
#Override
public void onDrawerStateChanged(int newState) {
super.onDrawerStateChanged(newState);
}
};
mDrawerLayout.setDrawerListener(actionBarDrawerToggle);
/**
* As we are calling BaseActivity from manifest file and this base activity is intended just to add navigation drawer in our app.
* We have to open some activity with layout on launch. So we are checking if this BaseActivity is called first time then we are opening our first activity.
* */
if(isLaunch){
/**
*Setting this flag false so that next time it will not open our first activity.
*We have to use this flag because we are using this BaseActivity as parent activity to our other activity.
*In this case this base activity will always be call when any child activity will launch.
*/
isLaunch = false;
openActivity(0);
}
}
/**
* #param position
*
* Launching activity when any list item is clicked.
*/
protected void openActivity(int position) {
/**
* We can set title & itemChecked here but as this BaseActivity is parent for other activity,
* So whenever any activity is going to launch this BaseActivity is also going to be called and
* it will reset this value because of initialization in onCreate method.
* So that we are setting this in child activity.
*/
mDrawerLayout.closeDrawer(mDrawerList);
BaseActivity.position = position; //Setting currently selected position in this field so that it will be available in our child activities.
switch (position) {
case 0:
startActivity(new Intent(this, Item1Activity.class));
break;
case 1:
startActivity(new Intent(this, Item2Activity.class));
break;
case 2:
startActivity(new Intent(this, Item3Activity.class));
break;
case 3:
startActivity(new Intent(this, Item4Activity.class));
break;
case 4:
startActivity(new Intent(this, Item5Activity.class));
break;
default:
break;
}
Toast.makeText(this, "Selected Item Position::"+position, Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#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 (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* 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_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/* We can override onBackPressed method to toggle navigation drawer*/
#Override
public void onBackPressed() {
if(mDrawerLayout.isDrawerOpen(mDrawerList)){
mDrawerLayout.closeDrawer(mDrawerList);
}else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
}
my pager adapter code (notice this pager class extends only the navigator, and the navigator extends activity...this will not work (your issue) if you change the "extends activity" in Navigator to "extends FragmentActivity" the pager and drawer will work. Because this view pager uses FragmentActivity):
public class StartActive extends Navigator implements TabListener
{
MyAdapter adapt;
ActionBar actionBar;
ViewPager viewPager = null;
String userName;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_start_active);
getLayoutInflater().inflate(R.layout.activity_start_active, frameLayout);
naviList.setItemChecked(position, true);
setTitle(category[position]);
if(getIntent().getExtras() != null)
{
userName = getIntent().getExtras().getString(MainActivity.KEY_USERNAME);
}
swipeTabs();
}
public void swipeTabs()
{
FragmentManager fragMan = getSupportFragmentManager();
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
adapt = new MyAdapter(fragMan);
viewPager = (ViewPager) findViewById(R.id.startActive_Activity);
viewPager.setAdapter(adapt);
viewPager.setOnPageChangeListener(new OnPageChangeListener()
{
#Override
public void onPageSelected(int arg0)
{
actionBar.setSelectedNavigationItem(arg0);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2)
{
}
#Override
public void onPageScrollStateChanged(int arg0)
{
}
});
android.app.ActionBar.Tab tab1 = actionBar.newTab();
tab1.setText("User");
tab1.setTabListener(this);
android.app.ActionBar.Tab tab2 = actionBar.newTab();
tab2.setText("Maps");
tab2.setTabListener(this);
android.app.ActionBar.Tab tab3 = actionBar.newTab();
tab3.setText("Feed");
tab3.setTabListener(this);
actionBar.addTab(tab1);
actionBar.addTab(tab2);
actionBar.addTab(tab3);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.start_active, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment
{
public PlaceholderFragment()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_start_active, container, false);
Log.d("Life cycles", "onCreateView");
return rootView;
}
}
#Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1)
{
viewPager.setCurrentItem(arg0.getPosition());
}
#Override
public void onTabSelected(Tab arg0, FragmentTransaction arg1)
{
viewPager.setCurrentItem(arg0.getPosition());
}
#Override
public void onTabUnselected(Tab arg0, FragmentTransaction arg1)
{
}
class MyAdapter extends FragmentPagerAdapter
{
public MyAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int arg0)
{
Bundle b = new Bundle();
b.putString(MainActivity.KEY_USERNAME, userName);
Fragment frag;
switch(arg0)
{
case 1:
return new GMaps();
case 0:
frag = new UserView();
frag.setArguments(b);
return frag;
case 2:
frag = new FeedView();
frag.setArguments(b);
return frag;
}
return null;
}
#Override
public int getCount()
{
return 3;
}
}
}
If you are looking for a Navigation Drawer on top of the ViewPager here's what you can do:
Incase if you don't know about the Navigationdrawer properly please check this link(Click Here)
use this code within your relative Layout
<android.support.v4.widget.DrawerLayout
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:id="#+id/custom_drawer_layout">
<RelativeLayout
android:id="#+id/relative"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<android.support.v4.view.PagerTabStrip
android:id="#+id/pager_tab_strip"
android:layout_width="match_parent"
android:layout_height="48sp"
android:layout_gravity="top"
android:background="#color/primary"
android:paddingBottom="20dp"
android:textAppearance="#style/PagerTabStripText" />
</android.support.v4.view.ViewPager>
</RelativeLayout>
<fragment
android:id="#+id/notification_drawer_fragement"
android:layout_width="260dp"
android:layout_height="match_parent"
android:layout_gravity="end"
android:name="address to fragment class"
tools:layout="#layout/notification_fragment"
/>
</android.support.v4.widget.DrawerLayout>
Here is what you will get:
1 is the fragment and 2 is the viewPager
I have to implement navigation drawer in my app activity but its not working.It is showing button for the drawer but its not responding.
Here is my code:
// ListView represents Navigation Drawer
private ListView mDrawerList;
private String[] drawerlist = { "Submit Task", "Edit Profile", "Log Out" };
// ActionBarDrawerToggle indicates the presence of Navigation Drawer in the
// action bar
private ActionBarDrawerToggle mDrawerToggle;
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "My profile", "Friend's posts", "Friend List",
"Top posts" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
getActionBar().setTitle("OTAKU");
// Getting reference to the DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
// Getting reference to the ActionBarDrawerToggle
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
/** Called when drawer is closed */
public void onDrawerClosed(View view) {
getActionBar().setTitle("OTAKU");
invalidateOptionsMenu();
}
/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle("OTAKU");
invalidateOptionsMenu();
}
};
// Setting DrawerToggle on DrawerLayout
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Creating an ArrayAdapter to add items to the listview mDrawerList
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.drawer_list_item, drawerlist);
// Setting the adapter on mDrawerList
mDrawerList.setAdapter(adapter);
// Enabling Home button
getActionBar().setHomeButtonEnabled(true);
// Enabling Up navigation
getActionBar().setDisplayHomeAsUpEnabled(true);
// Setting item click listener for the listview mDrawerList
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item))
return true;
if (item.getItemId() == R.id.action_search) {
Intent j = new Intent(getApplicationContext(), Searchresults.class);
startActivity(j);
return true;
}
return super.onOptionsItemSelected(item);
}
/** Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_search).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu1, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
I have doubts regarding onOptionsItemSelected(MenuItem item) method.
Here is layout file
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView
android:id="#+id/drawer_list"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>
In your onOptionsItemSelected method you aren't doing anything when the user clicks on your drawerToggle. You need to add code to open/close the drawer.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item))
// code to open/close drawer here
return true;
if (item.getItemId() == R.id.action_search) {
Intent j = new Intent(getApplicationContext(), Searchresults.class);
startActivity(j);
return true;
}
return super.onOptionsItemSelected(item);
}