Android: Navigation menu not working with button but with touch - android

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;
}
}

Related

Toggle menu Button doesn't open sliding menu and shuts down app

I have included DrawerLayout in my app. I have added Toolbar and "home button" into it. Sliding menu works fine except this "menu button" on the left of Toolbar. Problem is, when I click on it my app shuts down without reason. I have no idea why it shuts. It should open hidden sliding menu. If I swipe from left to right this menu shows up but when button is clicked it shuts down all app immediately.
Below is my menu XML code:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<include layout="#layout/activity_main_sliding_content_main" />
<!--
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>-->
<!-- The navigation drawer -->
<ListView android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
AND INCLUDED VIEW:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimaryDark"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
android:visibility="visible"/>
<ListView
android:id="#+id/listviewmain"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentEnd="true"
android:layout_above="#+id/adView"
android:layout_below="#+id/my_toolbar" />
<ProgressBar
android:id="#+id/progressbar"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
<TextView
android:id="#+id/progressText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:text="Name"
android:layout_below="#+id/progressbar"
android:layout_centerHorizontal="true"
android:textAlignment="center"
/>
<com.google.android.gms.ads.AdView
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
ads:adSize="BANNER"
ads:adUnitId="ca-app-pub-3940256099942544/6300978111"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true">
</com.google.android.gms.ads.AdView>
</RelativeLayout>
JAVA CODE BELOW:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
setContentView(R.layout.maincontent_slidingmenu);
mainRelativeLayout = (RelativeLayout) findViewById(R.id.mainRelativeLayout);
// mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
hiddenLayout = (RelativeLayout) findViewById(R.id.hiddenLayout);
myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
listView = (ListView) findViewById(R.id.listviewmain);
progressBar = (ProgressBar) findViewById(R.id.progressbar);
progressView = (TextView) findViewById(R.id.progressText);
setSupportActionBar(myToolbar);
setupSlidingMenu(savedInstanceState);
setUpActionBarDrawerToggle();
setOnClickListners();
loadDataIntoMmemory();
setUpAdds();
}
private void setupSlidingMenu(Bundle savedInstanceState)
{
mTitle = mDrawerTitle = getTitle();
menuTitles = getResources().getStringArray(R.array.titles);
menuIcons = getResources().obtainTypedArray(R.array.icons);
mDrawerList = (ListView) findViewById(R.id.left_drawer) ;
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < menuTitles.length; i++) {
RowItem items = new RowItem(menuTitles[i], menuIcons.getResourceId(
i, -1));
rowItems.add(items);
}
menuIcons.recycle();
customSlidingAdapter = new CustomSlidingMenuAdapter(getApplicationContext(), rowItems);
System.out.println(customSlidingAdapter.isEmpty());
mDrawerList.setAdapter(customSlidingAdapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
/*mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());*/
};
private void setUpActionBarDrawerToggle()
{
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//new ActionBarDrawerToggle(myToolbar,mDrawerLayout, R.string.opened, R.string.zamkniecie);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.string.opened, R.string.zamkniecie) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
myToolbar.setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
syncState();
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
myToolbar.setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
syncState();
}
#Override
public void setToolbarNavigationClickListener(View.OnClickListener onToolbarNavigationClickListener) {
super.setToolbarNavigationClickListener(onToolbarNavigationClickListener);
mDrawerLayout.openDrawer(mDrawerList);
}
};
// Set the drawer toggle as the DrawerListener
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerLayout.addDrawerListener(mDrawerToggle);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START); // OPEN DRAWER
return true;
case R.id.action_settings:
// User chose the "Settings" item, show the app settings UI...
return true;
case R.id.action_favorite:
// User chose the "Favorite" action, mark the current item
// as a favorite...
return true;
case R.id.action_searching:
/*// MenuItem searchItem = menu.findItem(R.id.action_searching);
//searchView = (SearchView) MenuItemCompat.getActionView();
searchView.setOnQueryTextListener(this);*/
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
//getActionBar().setTitle(mTitle);
myToolbar.setTitle(mTitle);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
//boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
//menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
mDrawerToggle.syncState();
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
// menu.findItem(R.id.left_drawer).setVisible(!drawerOpen);
// return super.onPrepareOptionsMenu(menu);
return super.onPrepareOptionsMenu(menu);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
// Sync the toggle state after onRestoreInstanceState has occurred.
// mDrawerToggle.syncState();
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// Pass any configuration change to the drawer toggls
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_searching);
searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(this);
return true;
}
replace your setUpActionBarDrawerToggle with below and check
private void setUpActionBarDrawerToggle()
{
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, myToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
myToolbar.setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
syncState();
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
myToolbar.setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
syncState();
}
#Override
public void setToolbarNavigationClickListener(View.OnClickListener onToolbarNavigationClickListener) {
super.setToolbarNavigationClickListener(onToolbarNavigationClickListener);
mDrawerLayout.openDrawer(GravityCompat.START);
}
};
mDrawerLayout.addDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
you don't need to add
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Toolbar empty with Navigation Drawer

My BaseDrawerActivity extends BaseActivity and I have a Toolbar in BaseActivity.
The toolbar shows with no issues in classes that extend BaseActivity, but ALL classes that extend BaseDrawerActivity just show a blank toolbar. The nav drawer works fine.
When I had one main activity class (BaseActivity + BaseDrawerActivity) the toolbar showed no problem and the nav drawer worked.
Why is my implementation here not showing the Toolbar? I debugged and getToolbar() is returning the toolbar for sure.
activity_base_drawer.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar"/>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:foreground="?android:windowContentOverlay">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<include layout="#layout/call_to_action_banner"/>
</FrameLayout>
<ListView
android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
style="#style/NavDrawerListView" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:theme="#style/ToolbarOverlay"
android:popupTheme="#style/ToolbarOverlay"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white"
android:minHeight="?attr/actionBarSize"
android:elevation="10dp"/>
BaseDrawerActivity
public abstract class BaseDrawerActivity extends BaseActivity {
private static final int LAYOUT_ID = R.layout.activity_base_drawer;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private NavDrawerAdapter mNavDrawerAdapter;
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)){
mDrawerLayout.closeDrawers();
} else {
super.onBackPressed();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(LAYOUT_ID);
setupNavDrawer();
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
private void setupNavDrawer() {
final ListView navDrawerListView = (ListView) findViewById(R.id.navigation_drawer);
View header = getLayoutInflater().inflate(R.layout.nav_drawer_header, null, false);
mNavDrawerAvatarImageView = (ImageView) header.findViewById(R.id.avatar);
mNavDrawerUsernameTextView = (CustomTextView) header.findViewById(R.id.username);
navDrawerListView.addHeaderView(header);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
getToolbar(),
R.string.navigation_drawer_open,
R.string.navigation_drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
updateNavDrawerUserInfo();
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mNavDrawerAdapter = new NavDrawerAdapter(this);
navDrawerListView.setAdapter(mNavDrawerAdapter);
navDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
mDrawerLayout.closeDrawer(GravityCompat.START);
onNavigationDrawerItemSelected(position);
}
});
updateNavDrawerUserInfo();
}
private void updateNavDrawerUserInfo() {
final DatabaseHelper db = DatabaseHelper.getInstance(this);
if (db.doesUserExist(SharedPrefs.getUserId())) {
final User currentUser = db.getUser(SharedPrefs.getUserId());
if (currentUser != null) {
if (currentUser.getAvatarType() != null) {
try {
mNavDrawerAvatarImageView.setImageDrawable(getResources().getDrawable(
ViewUtil.getAvatarHeadDrawableId(this,
currentUser.getAvatarType())));
} catch (Resources.NotFoundException e) {
e.printStackTrace();
}
}
if (currentUser.getUsername() != null) {
mNavDrawerUsernameTextView.setText(currentUser.getUsername());
}
}
}
}
}
BaseActivity
private void setupToolbar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle("");
getSupportActionBar().setSubtitle("");
getSupportActionBar().setLogo(R.drawable.logo_toolbar);
}
mUpdatingSpinner = (ProgressBar) getLayoutInflater().inflate(
R.layout.toolbar_updating_spinner, null, false);
int dpInPixels = (int) getResources().getDimension(R.dimen.toolbar_updating_spinner);
Toolbar.LayoutParams spinnerLp = new Toolbar.LayoutParams(dpInPixels, dpInPixels,
Gravity.END);
mToolbar.addView(mUpdatingSpinner, spinnerLp);
}
I found the answer although I don't fully understand it.
I basically called setupToolbar() again in my BaseDrawerActivity right before I call setupNavDrawer() and for some reason this fixed it.
I think the reference to the Toolbar from BaseActivity wasn't retrieving correctly (even though I debugged and it had a reference to it). Another thing I tried is setSupportActionBar(mToolbar) right before setting up the nav drawer but that didn't work.
If anyone has any ideas as to why I have to setup the toolbar again in order for it to show I'd be glad to hear it!
go to the AndroidManifest.xml file and replace
android:theme="#style/AppTheme"
with
android:theme="#android:style/Theme.Holo.Light.DarkActionBar"
you have to use setSupportActionBar(Toolbar toolbar).
This question should help.

Add icon in navigation Drawer

I have a navigation drawer and i want to add icon. But i dont know how to implement it. Is there any way i can customize my list inside navigation drawer? and use menu instead of array for items inside the navigation drawer. Thanks in advance :)
Heres my code :
public class MainActivity extends ActionBarActivity {
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.activity_main);
mDrawerList = (ListView)findViewById(R.id.navList);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, new One()).commit();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
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() {
Fragment fragment = null;
Class fragmentClass;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 1:
fragmentClass = One.class;
break;
case 2:
fragmentClass = Two.class;
break;
default:
break;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager=getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
// Highlight the selected item, update the title, and close the drawer
mDrawerLayout.closeDrawers();
}
});
}
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_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Inside your navigation Drawer xml file add menu file app:menu="#menu/activity_main_drawer"
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:menu="#menu/activity_main_drawer">
</android.support.design.widget.NavigationView>
in activity_main_drawer menu file define your icons wrt their names
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item android:id="#+id/nav_camara" android:icon="#android:drawable/ic_menu_camera"
android:title="Camera" />
<item android:id="#+id/nav_gallery" android:icon="#android:drawable/ic_menu_gallery"
android:title="Gallery" />
<item android:id="#+id/nav_manage" android:icon="#android:drawable/ic_menu_manage"
android:title="Manage" />
</group>
In your MainActivity.java call the action of each item click of drawer menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// Handle navigation view item clicks here.
int id = menuItem.getItemId();
if (id == R.id.nav_camara) {
// Call your Action
} else if (id == R.id.nav_gallery) {
// Call your Action
} else if (id == R.id.nav_manage) {
// Call your Action
}
}
Yes, just create your custom layout for drawer list item.
Check answer f.e. here How to add icons to items in a navigation drawer
In your case you have to create your own adapter instead of ArrayAdapter and your custom item list view, that will contain ImageView for icon.

Navigation Drawer in multiple activities does not work

I'm trying to use NavigationDrawer on my activity (Home), but the content of activity is not shown.
home_activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/home_activity">
<Button
android:id="#+id/like_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="likeCounter"
android:background="#drawable/likecountgreen" />
</LinearLayout>
activity_drawer.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">
</FrameLayout>
<ListView
android:id="#+id/nav_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#fff"
android:choiceMode="singleChoice" />
HomeActivity.class
public class HomeActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_activity);
super.onCreateDrawer();
}
}
BaseActivity.class
public class BaseActivity extends ActionBarActivity implements AdapterView.OnItemClickListener {
private ListView drawerList;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private String[] options;
private TextView titleActionBar;
protected void onCreateDrawer() {
setContentView(R.layout.activity_drawer);
setupActionBar();
options = getResources()
.getStringArray(R.array.drawer_options);
drawerLayout =
(DrawerLayout) findViewById(R.id.drawer_layout);
drawerList = (ListView) findViewById(R.id.nav_drawer);
drawerList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, options));
drawerList.setOnItemClickListener(this);
setupDrawer();
}
private void setupActionBar() {
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.action_bar);
titleActionBar = (TextView) findViewById(R.id.title_action_bar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
titleActionBar.setText("App");
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
titleActionBar.setText("Options");
invalidateOptionsMenu();
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
drawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 2:
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out);
drawerLayout.closeDrawer(drawerList);
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.home_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_search) {
return true;
}
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
What I've discovered is that drawer_activity is overlaying home_activity.
How can I solve it?
In onCreateDrawer you are setting a new layout, so your layout that you set in your MainActivity is not shown anymore. Here is how you can solve this:
HomeActivity:
public class HomeActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.onCreateDrawer(R.layout.home_activity);
}
}
And in your BaseActivity:
protected FrameLayout content;
protected void onCreateDrawer(final int layoutResID) {
setContentView(R.layout.activity_drawer);
content = (FrameLayout) findViewById(R.id.content_frame);
getLayoutInflater().inflate(layoutResID, content, true);
setupActionBar();
options = getResources()
.getStringArray(R.array.drawer_options);
drawerLayout =
(DrawerLayout) findViewById(R.id.drawer_layout);
drawerList = (ListView) findViewById(R.id.nav_drawer);
drawerList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, options));
drawerList.setOnItemClickListener(this);
setupDrawer();
}
Now the FrameLayout in your activity_drawer layout contains the layout of your HomeActivity.

NavigationDrawer icon not showing up

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);
}

Categories

Resources