Navigation drawer Fragment Issue - android

Hi i have this problem with my navigation drawer. The drawer opens fine but i am having problems with the onClickListener. if an item on the drawer is clicked on it doesnt show the related layout instaed a black page shows. Please help
home.java
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.Toast;
public class home extends AppCompatActivity {
//Defining Variables
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Initializing Toolbar and setting it as the actionbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing NavigationView
navigationView = (NavigationView) findViewById(R.id.navigation_view);
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not make it in checked state
if(menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()){
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.dashboard:
Toast.makeText(getApplicationContext(),"dashboard",Toast.LENGTH_SHORT).show();
Dashboard fragment = new Dashboard();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame,fragment);
fragmentTransaction.commit();
break;
// For rest of the options we just show a toast on click
case R.id.profile:
Toast.makeText(getApplicationContext(),"profile",Toast.LENGTH_SHORT).show();
new Profile();
break;
case R.id.logs:
Toast.makeText(getApplicationContext(),"logs",Toast.LENGTH_SHORT).show();
new Logs();
break;
case R.id.statements:
Toast.makeText(getApplicationContext(),"statements",Toast.LENGTH_SHORT).show();
new Statements();
break;
case R.id.timeline:
Toast.makeText(getApplicationContext(),"timeliine",Toast.LENGTH_SHORT).show();
new Timeline();
break;
case R.id.settings:
Toast.makeText(getApplicationContext(),"settings",Toast.LENGTH_SHORT).show();
new Settings();
break;
default:
Toast.makeText(getApplicationContext(),"Somethings Wrong",Toast.LENGTH_SHORT).show();
break;
}
return true; }
});
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.openDrawer, R.string.closeDrawer){
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessay or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

You're not switching fragments correctly in your case statements. You're only instantiating a new Fragment class and not doing anything with it. You need to do something like this:
Fragment fragment;
switch (menuItem.getItemId()){
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.dashboard:
Toast.makeText(getApplicationContext(),"dashboard",Toast.LENGTH_SHORT).show();
fragment = new Dashboard();
break;
// For rest of the options we just show a toast on click
case R.id.profile:
Toast.makeText(getApplicationContext(),"profile",Toast.LENGTH_SHORT).show();
fragment = new Profile();
break;
case R.id.logs:
Toast.makeText(getApplicationContext(),"logs",Toast.LENGTH_SHORT).show();
fragment = new Logs();
break;
case R.id.statements:
Toast.makeText(getApplicationContext(),"statements",Toast.LENGTH_SHORT).show();
fragment = new Statements();
break;
case R.id.timeline:
Toast.makeText(getApplicationContext(),"timeliine",Toast.LENGTH_SHORT).show();
fragment = new Timeline();
break;
case R.id.settings:
Toast.makeText(getApplicationContext(),"settings",Toast.LENGTH_SHORT).show();
fragment = new Settings();
break;
default:
Toast.makeText(getApplicationContext(),"Somethings Wrong",Toast.LENGTH_SHORT).show();
break;
}
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame,fragment);
fragmentTransaction.commit();
This way you're instantiating a fragment with a proper Fragment class each time, and at the end, replacing the frame with that particular fragment.
Digresion: It is recommended that you use newInstance to get the fragments and not the constructor. This is known as the Singleton design pattern.

Related

new activity won't start after clicked navigation drawer

I am aware that this question exists but the answers don't work for my case.
I have a navigation drawer with four items, but when I click on the first one (the one i'm working on right now), the new activity I created doesn't open, I have looked and tried everything I found on the internet but nothing seems to work.
i'm kinda new to android studio so I really don't know how to fix this. The android studio version I am using is 3.0.
This is my menu xml:
<?xml version="1.0" encoding="utf-8"?>
<!--Icons made by http://www.freepik.com
from "https://www.flaticon.com
is licensed by http://creativecommons.org/licenses/by/3.0/-->
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/m1" android:title="Agora Mall"
android:icon="#drawable/ic_ammunition"/>
<item android:id="#+id/m2" android:title="Downtown Center"
android:icon="#drawable/ic_ammunition"/>
<item android:id="#+id/m3" android:title="Galeria 360"
android:icon="#drawable/ic_ammunition"/>
<item android:id="#+id/m4" android:title="Sambil"
android:icon="#drawable/ic_ammunition"/>
</menu>
this is the main activity class code:
package com.example.arlet.storemaps;
import android.content.Intent;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.Window;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)) {
return true;
}
switch(item.getItemId()){
case R.id.m1:
Intent intent = new Intent(MainActivity.this, AgoraActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
You must implement onNavigationItemSelected() for the navigation drawer menu.
onOptionsItemSelected() is related to the toolbar options menu items.
You can find all the necessary code for this if you create a new project and choose
Navigation Drawer Activity
as the type of your MainActivity.
You Can handle navigation drawer item click in following way:
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.m1:
Intent intent = new Intent(MainActivity.this, AgoraActivity.class);
startActivity(intent);
return true;
break;
case R.id.m2:
break;
case R.id.m3:
break;
case R.id.m4:
break;
}
menuItem.setChecked(true);
return true;
}
});
You must implement NavigationView.OnNavigationItemSelectedListener for the drawer items to work perfectly
Add this to your class declaration
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
// then overide this method to
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id){
case R.id.m1:
Intent intent = new Intent(MainActivity.this, AgoraActivity.class);
startActivity(intent);
return true;
//other cases goes here
}
return super.onOptionsItemSelected(item);
}
//you might want to ovewrite this method too
#Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}

Navigation Drawer for multiple Activities not working on item click

Hey Guys I read this thread a while ago and tried to replicate it since i'm using multiple activities within my app.
I copied all my code for the navigation drawer within my new NavigationDrawerActivity.java which looks like this:
package info.androidhive.navigationdrawer.activity;
import android.content.Intent;
import android.os.Handler;
import android.support.annotation.LayoutRes;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
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.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import info.androidhive.navigationdrawer.R;
import info.androidhive.navigationdrawer.fragment.CameraFragment;
import info.androidhive.navigationdrawer.fragment.ExposeDetailFragment;
import info.androidhive.navigationdrawer.fragment.HomeFragment;
import info.androidhive.navigationdrawer.fragment.MyAccountFragment;
import info.androidhive.navigationdrawer.fragment.SettingsFragment;
public class NavigationDrawerActivity extends AppCompatActivity {
public DrawerLayout drawerLayout;
public NavigationView navigationView;
public DrawerLayout drawer;
public View navHeader;
public TextView txtName;
public TextView txtWebsite;
public Toolbar toolbar;
// index to identify current nav menu item
public static int navItemIndex = 0;
// tags used to attach the fragments
public static final String TAG_HOME = "home";
public static final String TAG_CAMERA = "camera";
public static final String TAG_MOVIES = "movies";
public static final String TAG_MY_ACCOUNT = "myaccoount";
public static final String TAG_SETTINGS = "settings";
public static String CURRENT_TAG = TAG_HOME;
// toolbar titles respected to selected nav menu item
public String[] activityTitles;
// flag to load home fragment when user presses back key
public boolean shouldLoadHomeFragOnBackPress = true;
public Handler mHandler;
#Override
public void setContentView(#LayoutRes int layoutResID) {
drawerLayout = (DrawerLayout) getLayoutInflater().inflate(R.layout.activity_navigation_drawer,null);
getLayoutInflater().inflate(layoutResID,drawerLayout,true);
super.setContentView(drawerLayout);
//DrawerContent here
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mHandler = new Handler();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
// Navigation view header
navHeader = navigationView.getHeaderView(0);
txtName = (TextView) navHeader.findViewById(R.id.name);
txtWebsite = (TextView) navHeader.findViewById(R.id.webseite);
// load toolbar titles from string resources
activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);
// load nav menu header data
loadNavHeader();
// initializing navigation menu
setUpNavigationView();
}
/***
* Load navigation menu header information
* like background image, profile image
* name, website, notifications action view (dot)
*/
private void loadNavHeader() {
// name, website
txtName.setText("Ravi Tamada");
txtWebsite.setText("www.androidhive.info");
}
/***
* Returns respected fragment that user
* selected from navigation menu
*/
public void loadHomeFragment() {
// selecting appropriate nav menu item
selectNavMenu();
// set toolbar title
setToolbarTitle();
// if user select the current navigation menu again, don't do anything
// just close the navigation drawer
if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
drawer.closeDrawers();
return;
}
// Sometimes, when fragment has huge data, screen seems hanging
// when switching between navigation menus
// So using runnable, the fragment is loaded with cross fade effect
// This effect can be seen in GMail app
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
// update the main content by replacing fragments
Fragment fragment = getHomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commitAllowingStateLoss();
}
};
// If mPendingRunnable is not null, then add to the message queue
if (mPendingRunnable != null) {
mHandler.post(mPendingRunnable);
}
/*FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Click action
Intent intent = new Intent(NavigationDrawerActivity.this, NewExposeActivity.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Ein neues Exposé erstellen", Toast.LENGTH_LONG).show();
}
});*/
//Closing drawer on item click
drawer.closeDrawers();
// refresh toolbar menu
invalidateOptionsMenu();
}
public Fragment getHomeFragment() {
switch (navItemIndex) {
case 0:
// home
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
case 1:
// expose List
HomeFragment homeFragment1 = new HomeFragment();
return homeFragment1;
case 2:
//Camera fragment
CameraFragment cameraFragment = new CameraFragment();
return cameraFragment;
case 3:
// notifications fragment
MyAccountFragment myAccountFragment = new MyAccountFragment();
return myAccountFragment;
case 4:
// settings fragment
SettingsFragment settingsFragment = new SettingsFragment();
return settingsFragment;
default:
return new HomeFragment();
}
}
public void setToolbarTitle() {
getSupportActionBar().setTitle(activityTitles[navItemIndex]);
}
public void selectNavMenu() {
navigationView.getMenu().getItem(navItemIndex).setChecked(true);
}
public void setUpNavigationView() {
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.home:
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
break;
case R.id.nav_camera:
navItemIndex = 1;
CURRENT_TAG = TAG_CAMERA;
break;
case R.id.nav_movies:
navItemIndex = 2;
CURRENT_TAG = TAG_MOVIES;
break;
case R.id.nav_my_account:
navItemIndex = 3;
CURRENT_TAG = TAG_MY_ACCOUNT;
break;
case R.id.nav_settings:
navItemIndex = 4;
CURRENT_TAG = TAG_SETTINGS;
break;
case R.id.nav_rss:
startActivity( new Intent(NavigationDrawerActivity.this, RSSFeedActivity.class));
drawer.closeDrawers();
return true;
case R.id.nav_login:
startActivity( new Intent(NavigationDrawerActivity.this, LoginActivity.class));
drawer.closeDrawers();
return true;
default:
navItemIndex = 0;
}
//Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked()) {
menuItem.setChecked(false);
} else {
menuItem.setChecked(true);
}
menuItem.setChecked(true);
loadHomeFragment();
return true;
}
});
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawer.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessary or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawers();
return;
}
// This code loads home fragment when back key is pressed
// when user is in other fragment than home
if (shouldLoadHomeFragOnBackPress) {
// checking if user is on other navigation menu
// rather than home
if (navItemIndex != 0) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
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;
}
#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.add_expose) {
Toast.makeText(getApplicationContext(), "Ein neues Exposé soll erstellt werden!", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
}
and here the activity_navigation_drawer.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" >
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
here is the activity_navigation_drawer.xml which is menu Ressource file:
<?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_home"
android:icon="#drawable/ic_home_black_24dp"
android:title="#string/nav_home" />
<item
android:id="#+id/nav_camera"
android:icon="#mipmap/ic_list_black_24dp"
android:title="#string/nav_photos" />
<item
android:id="#+id/nav_movies"
android:icon="#mipmap/ic_camera_alt_black_24dp"
android:title="#string/nav_movies" />
<item
android:id="#+id/nav_my_account"
android:icon="#mipmap/ic_person_black_24dp"
android:title="Mein Account" />
<item
android:id="#+id/nav_settings"
android:icon="#mipmap/ic_settings_black_24dp"
android:title="#string/nav_settings" />
</group>
<item android:title="Other">
<menu>
<item
android:id="#+id/nav_rss"
android:title="News"
android:icon="#mipmap/ic_rss_feed_black_24dp" />
<item
android:id="#+id/nav_login"
android:title="#string/action_logout"
android:icon="#mipmap/ic_lock_black_24dp" />
</menu>
</item>
</menu>
It's working great up to the fact that when i click an item in the navigation nothing happens. Are there any suggestions to what I'm doing wrong.
You can find the whole project here.
Thanks for your help.
First , post a reference or code to how you are creating the menu item , do u create it in the resources menu file or simply load an array , If you are using array then i would suggest you to use menu xml to create menu items.
Something like this:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/new_game"
android:icon="#drawable/ic_new_game"
android:title="#string/new_game"
android:showAsAction="ifRoom"/>
<item android:id="#+id/help"
android:icon="#drawable/ic_help"
android:title="#string/help" />
</menu>
also make corresponding changes in ur code,check
https://developer.android.com/guide/topics/ui/menus.html
https://developer.android.com/training/implementing-navigation/nav-drawer.html

how to go back to previous fragment when hardware back button is pressed

i am begineer in android development , i would like to configure hardware backbutton to go back to previous fragment and the fragment titles should also change according to the current fragment ,
here is my Main activity source :
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
#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;
}
if(id == R.id.action_search){
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case 1:
fragment = new MicrosoftDskFragment();
title = "Microsoft Dsk";
break;
case 2:
fragment = new GoogleDskFragment();
title = "Google Dsk";
break;
case 3:
fragment = new AppleDskFragment();
title = "Apple Dsk";
break;
case 4:
fragment = new OthersDskFragment();
title = "Others Dsk";
break;
case 5:
fragment = new AboutUSFragment();
title = "About US";
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.addToBackStack(null).commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
}
plz hel me in fixing this .
You are adding the transaction to the backstack, so all you should need in order to get back to the previous one should be:
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.popBackstack(null, 0);
You may also consider adding an id for each fragment and passing it when calling
fragmentTransaction.addToBackStack(null).commit();
instead of the null. This way, you will be able to do this:
fragmentTransaction.addToBackStack(myFragmentId).commit();
//Later on...
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.popBackstack(myFragmentId, 0);
To go back to a specific fragment, not just the last one :-)
every time when you add a fragment just add addToBackStack() method before commit and then in your activity on back pressed try this
public void onBackPressed() {
int count = getSupportFragmentManager().getBackStackEntryCount();
if (count == 1) {
goToExitApplication(
getResources().getString(R.string.close_app), true);
} else {
String title = getSupportFragmentManager().getBackStackEntryAt(count - 2).getName();
getSupportFragmentManager().popBackStack();
getSupportActionBar().setTitle(title);
}
}
I have used this in my code:
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0 ){
getSupportFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
To push the Fragment I used:
MyFragment_Items myf = new MyFragment_Items();
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container_layout, myf);
transaction.addToBackStack(null);
transaction.commit();
I pushed the fragment here and popped it back onBackPressed.
It will Surely work for you If there is any Fragment on the back stack of current fragment , popBackStackImmediate() works..
#Override
public void onBackPressed() {
if(getFragmentManager().getBackStackEntryCount() > 0){
getFragmentManager().popBackStackImmediate();
}
else{
super.onBackPressed();
}
}

Android click listener

java i am having trouble with the switch statement part of the code. it doesn't seem to take me to the page which is been clicked on. Only the dashboard shows and each layout has already been created help please
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
public class home extends AppCompatActivity {
//Defining Variables
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Initializing Toolbar and setting it as the actionbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing NavigationView
navigationView = (NavigationView) findViewById(R.id.navigation_view);
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.dashboard:
Toast.makeText(getApplicationContext(), "Inbox Selected", Toast.LENGTH_SHORT).show();
Dashboard fragment = new Dashboard();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, fragment);
fragmentTransaction.commit();
return true;
// For rest of the options we just show a toast on click
case R.id.profile:
Toast.makeText(getApplicationContext(), "Profile Selected", Toast.LENGTH_SHORT).show();
new Profile();
return true;
case R.id.logs:
Toast.makeText(getApplicationContext(), "Logs Selected", Toast.LENGTH_SHORT).show();
new Logs();
return true;
case R.id.statements:
Toast.makeText(getApplicationContext(), "Statements Selected", Toast.LENGTH_SHORT).show();
new Statements();
return true;
case R.id.timeline:
Toast.makeText(getApplicationContext(), "TImeline Selected", Toast.LENGTH_SHORT).show();
new Timeline();
return true;
case R.id.settings:
Toast.makeText(getApplicationContext(), "Settings Selected", Toast.LENGTH_SHORT).show();
new Settings();
return true;
case R.id.logout:
Toast.makeText(getApplicationContext(), "Logout Selected", Toast.LENGTH_SHORT).show();
return true;
default:
Toast.makeText(getApplicationContext(), "Somethings Wrong", Toast.LENGTH_SHORT).show();
return true;
}
}
});
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessay or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"home Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://www.arkounting.com.ng.finark/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"home Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://www.arkounting.com.ng.finark/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
}
I think this is how your switch statement should look like:
switch (menuItem.getItemId()) {
//Replacing the main content with ContentFragment Which is our Inbox View;
Fragment fragment = null;
case R.id.dashboard:
Toast.makeText(getApplicationContext(), "Inbox Selected", Toast.LENGTH_SHORT).show();
fragment = new Dashboard();
break;
case R.id.profile:
Toast.makeText(getApplicationContext(), "Profile Selected", Toast.LENGTH_SHORT).show();
fragment = new Profile();
break;
case R.id.logs:
Toast.makeText(getApplicationContext(), "Logs Selected", Toast.LENGTH_SHORT).show();
fragment = new Logs();
return true;
case R.id.statements:
Toast.makeText(getApplicationContext(), "Statements Selected", Toast.LENGTH_SHORT).show();
fragment = new Statements();
break;
case R.id.timeline:
Toast.makeText(getApplicationContext(), "TImeline Selected", Toast.LENGTH_SHORT).show();
fragment = new Timeline();
break;
case R.id.settings:
Toast.makeText(getApplicationContext(), "Settings Selected", Toast.LENGTH_SHORT).show();
fragment = new Settings();
return true;
case R.id.logout:
Toast.makeText(getApplicationContext(), "Logout Selected", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(getApplicationContext(), "Somethings Wrong", Toast.LENGTH_SHORT).show();
break;
if (fragment != null) {
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, fragment);
fragmentTransaction.commit();
return true;
} else {
return true;
}
}

Fragment Navigation Drawer

I read this post :
I try to do it but i have trouble in the "Navigating between Menu Items" section.
Where do the code of this section go ? In the MainActivity.java file or else?
When i paste it on my IDE (Android Studio 1.4) the items "nvDrawer" and "NavigationView" are red:
Also, i have two onCreate() on the same file.
Can you give me some suggestions how to make it work?
Below the code of my MainActivity.java.
package com.ther01s.android.ma0;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawer;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set a Toolbar to replace the ActionBar.
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Find our drawer view
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
switch (item.getItemId()) {
case android.R.id.home:
mDrawer.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
// Make sure this is the method with just `Bundle` as the signature
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// Find our drawer view
nvDrawer = (NavigationView) findViewById(R.id.nvView);
// Setup drawer view
setupDrawerContent(nvDrawer);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the planet to show based on
// position
Fragment fragment = null;
Class fragmentClass;
switch(menuItem.getItemId()) {
case R.id.nav_first_fragment:
fragmentClass = FirstFragment.class;
break;
default:
fragmentClass = FirstFragment.class;
}
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
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawer.closeDrawers();
}
}
Install latest android studio . then go to File --> New Project-->Configure your Project-->Target Device-->Choose Navigation Drawer Activity--> finish. You will get an awesome template from Android studio itself. Dont be confused by looking up for other useless tutorials.

Categories

Resources