Android studio 2.2.3 back button activity - android

I have created a demo app which comprises menu drawer and the tabbed activity in a same window by using drawer layout.The problem is when i select the fragments in the drawer menu it redirects its relevant fragment page but when tap back button the tabbed activity automatically disappeared and my app came out.how do i fix this issue? this is my main activity code
import android.content.Intent;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
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.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
//Button signIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mNavigationView = (NavigationView) findViewById(R.id.shitstuff) ;
/**
* Lets inflate the very first fragment
* Here , we are inflating the TabFragment as the first Fragment
*/
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();
/**
* Setup click events on the Navigation View Items.
*/
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
if (menuItem.getItemId() == R.id.nav_item_income) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.containerView,new IncomeFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_expence) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();
}
return false;
}
});
/**
* Setup Drawer Toggle of the Toolbar
*/
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout, toolbar,R.string.app_name,
R.string.app_name);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
}
This is my tab activity
package com.example.arunbhaskar.seconddemo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by arun.bhaskar on 2/9/2017.
*/
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 3 ;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
/**
*Inflate tab_layout and setup Views.
*/
View x = inflater.inflate(R.layout.tablayout,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
/**
*Set an Apater for the View Pager
*/
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
/**
* Now , this is a workaround ,
* The setupWithViewPager dose't works without the runnable .
* Maybe a Support Library Bug .
*/
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new Pie chart();
case 1 : return new Graph();
case 2 : return new Transaction();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "pie-chart";
case 1 :
return "Graph";
case 2 :
return "Transactions";
}
return null;
}
}
}

First add your fragment in backStack:
if (menuItem.getItemId() == R.id.nav_item_income) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null) //this line is needed
fragmentTransaction.replace(R.id.containerView,new IncomeFragment()).commit();
}
Now in your activity: overWrite the onBackPressed() method
#Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
Log.i("MainActivity", "popping backstack");
fm.popBackStack();
} else {
Log.i("MainActivity", "nothing on backstack, calling super");
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finishAffinity();
}
})
.setNegativeButton("No", null)
.show();
}
}

when you call any fragment you have to add that. Like below
mFragmentTransaction.addToBackStack("your_fregment_tag").commit();
and when backpress. This code
#Override
public void onBackPressed() {
try {
int backStackEntryCount = getSupportFragmentManager().getBackStackEntryCount();
if (mDrawerLayout.isDrawerOpen(GravityCompat.END)) {
mDrawerLayout.closeDrawer(GravityCompat.END);
return;
} else {
if (backStackEntryCount == 0) { // last fragment
android.app.AlertDialog.Builder alertDialog = new android.app.AlertDialog.Builder(DashboardActivity.this);
alertDialog.setTitle("Exit");
alertDialog.setMessage("Are you sure you want to Exit?");
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//finish();
//System.exit(0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
finishAffinity();
}else{
finish();
System.exit(0);
}
}
});
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
return;
}
}
} catch (Exception e) {
e.printStackTrace();
}
super.onBackPressed();
}
try using backStack. you have to trigger it. Please check my code

Create an onbackpress function your main activity
for example like this
#Override
public void onBackPressed() {
if (count == 1) {
if (exit) {
super.onBackPressed();
return;
} else {
Toast.makeText(this, "Press Back again to Exit.", Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 2000);
}
}else {
toolbar.setTitle("Home");
mDrawerLayout.closeDrawers();
count=1;
display(0);
}
}
set count of your home fragment as "1" and other intger for other fragments

update your NavigationItemSelectedListener with this.
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
if (menuItem.getItemId() == R.id.nav_item_income) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
IncomeFragment fragment = new IncomeFragment();
String fragClassName = fragment.getClass().getName();
fragmentTransaction.replace(R.id.containerView, fragment).addToBackStack(fragClassName).commit();
}
if (menuItem.getItemId() == R.id.nav_item_expence) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
TabFragment fragment = new TabFragment();
String fragClassName = fragment.getClass().getName();
xfragmentTransaction.replace(R.id.containerView, fragment).addToBackStack(fragClassName).commit();
}
return false;
}
});

Related

Expandable Navigation Drawer is not Working in Sub Items

I created Expandable List View for navigation drawer. it is working but when i select any item from it then it will close the drawer but when it has some Sub Items on that then also it will closing the drawer.
i.e. i have drawer like this
**Home**
**payment**
**delivery**
**order --> pending order --> complete order**
**exit**
when i select Home then it is working fine but when i click on order then it will close the drawer..
i want like when i click on order then the drawer remains open and when i select sub item then it will close.
here the complete code is as follow :-
NavigationDrawerFragment.java
package omcommunication.omprivillege;
/**
* Created by sachin on 3/9/2017.
*/
import android.content.Intent;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
public class NavigationDrawerFragment extends Fragment {
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private NavigationDrawerCallbacks mCallbacks;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ExpandableListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
ArrayList<String> groupItem = new ArrayList<String>();
ArrayList<Object> childItem = new ArrayList<Object>();
List<String> expandableListTitle;
HashMap<String, List<String>> expandableListDetail;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ExpandableListView) inflater.inflate(
R.layout.drawer_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
expandableListDetail = ExpandableListDataPump.getData();
expandableListTitle = new ArrayList<String>(expandableListDetail.keySet());
mDrawerListView.setAdapter(new ExpandableListAdapter(getActivity(), expandableListTitle, expandableListDetail));
mDrawerListView.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
}
});
mDrawerListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
boolean retVal = true;
if (groupPosition == ExpandableListAdapter.ITEM1) {
FragmentTransaction t = getFragmentManager().beginTransaction();
Homepage mFrag = new Homepage ();
t.replace(R.id.container, mFrag);
t.commit();
} else if (groupPosition == ExpandableListAdapter.ITEM2) {
FragmentTransaction t = getFragmentManager().beginTransaction();
Rorder mFrag = new Rorder();
t.replace(R.id.container, mFrag);
t.commit();
} else if (groupPosition == ExpandableListAdapter.ITEM3) {
FragmentTransaction t = getFragmentManager().beginTransaction();
Dispatchorder mFrag = new Dispatchorder();
t.replace(R.id.container, mFrag);
t.commit();
// retVal = false;
// call some activity here
} else if (groupPosition == ExpandableListAdapter.ITEM4) {
// call some activity here
retVal = false;
}else if (groupPosition == ExpandableListAdapter.ITEM5) {
// call some activity here
//retVal = false;
FragmentTransaction t = getFragmentManager().beginTransaction();
RecordDeliver mFrag = new RecordDeliver();
t.replace(R.id.container, mFrag);
t.commit();
}else if (groupPosition == ExpandableListAdapter.ITEM6) {
// call some activity here
//retVal = false;
FragmentTransaction t = getFragmentManager().beginTransaction();
OrderDelivery mFrag = new OrderDelivery();
t.replace(R.id.container, mFrag);
t.commit();
}else if (groupPosition == ExpandableListAdapter.ITEM7) {
// call some activity here
//retVal = false;
}else if (groupPosition == ExpandableListAdapter.ITEM8) {
// call some activity here
//retVal = false;
}else if (groupPosition == ExpandableListAdapter.ITEM9) {
// call some activity here
//retVal = false;
}
return retVal;
}
});
mDrawerListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
if (groupPosition == ExpandableListAdapter.ITEM1) {
if (childPosition == ExpandableListAdapter.SUBITEM1_1) {
Intent i = new Intent(getContext(), MainActivity.class);
startActivity(i);
}
else if (childPosition == ExpandableListAdapter.SUBITEM1_2) {
// call activity here
}
} else if (groupPosition == ExpandableListAdapter.ITEM2) {
if (childPosition == ExpandableListAdapter.SUBITEM2_1) {
// call activity here
}
else if (childPosition == ExpandableListAdapter.SUBITEM2_2) {
// call activity here
}
else if (childPosition == ExpandableListAdapter.SUBITEM2_3) {
// call activity here
}
else if (childPosition == ExpandableListAdapter.SUBITEM2_4) {
// call activity here
}
}
return true;
}
});
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
View header= inflater.inflate(R.layout.drawer_header, null);
mDrawerListView.addHeaderView(header);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.header, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActionBar().setIcon(R.drawable.header);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
/* if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.menu_main, menu);
showGlobalContextActionBar();
}
*/ super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
}
private ActionBar getActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
i refer many tutorial for it but not find my problem.. please help me out from this.
mDrawerLayout.closeDrawer(mDrawerListView);
set this line of code at the end of your group and child selection method.
drawerLayout.closeDrawer(mFragmentContainerView);
return retVal;
close the drawer inside your listener.

How to write the User name in the Navigation Drawer of a navigational activity From One of its Fragments?

HomeActivity.java (Navigational Activity)
import android.app.Fragment;
import android.app.FragmentManager;
mport android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.example.dellpc.reuz_app.DTO.User;
import com.example.dellpc.reuz_app.Fragments.BrowseAdFragment;
import com.example.dellpc.reuz_app.Fragments.LoginFragment;
import com.example.dellpc.reuz_app.Fragments.NetworkErrorFragment;
import com.example.dellpc.reuz_app.Fragments.TopMainFragment;
import com.example.dellpc.reuz_app.R;
import com.example.dellpc.reuz_app.utils.CheckNetworkConnection;
import com.example.dellpc.reuz_app.utils.NetworkErrorFragmentSetter;
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private Fragment fragment;
private String title;
private DrawerLayout drawer;
private NavigationView navigationView;
private View layout;
private User user=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle("REUZ");
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.bringToFront();
System.out.println(getSupportActionBar().getHeight());
View headerLayout = navigationView.getHeaderView(0);
layout=headerLayout.findViewById(R.id.navigationHeader);
getSupportActionBar().setTitle("REUZ");
this.setInitialFragment();
this.listeners();
/*this.getUserObject();*/
}
public void listeners(){
layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(CheckNetworkConnection.isConnectionAvailable(HomeActivity.this))
{
getLoginFragment();
}
else{
fragment= NetworkErrorFragmentSetter.getNetworkErrorFragment(HomeActivity.this);
replaceFragment();
}
}
});
getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
Fragment currentFragment = getFragmentManager().findFragmentById(R.id.content_frame);
if (currentFragment instanceof TopMainFragment) {
getSupportActionBar().setTitle("REUZ");
}
else if (currentFragment instanceof BrowseAdFragment) {
getSupportActionBar().setTitle("All Categories");
}
else if (currentFragment instanceof LoginFragment) {
getSupportActionBar().setTitle("LOGIN");
}
else if(currentFragment instanceof NetworkErrorFragment){
getSupportActionBar().setTitle("NETWORK ERROR");
}
}
});
}
#Override
public void onBackPressed() {
//drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
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.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
// Handle the home action
setInitialFragment();
} else if (id == R.id.nav_browse) {
fragment=new BrowseAdFragment();
} else if (id == R.id.nav_submitAd) {
Intent intent=new Intent(getApplicationContext(),SubmitAdActivity.class);
startActivity(intent);
} else if (id == R.id.nav_help) {
} else if (id == R.id.nav_my_ads) {
} else if (id == R.id.nav_wishList) {
}
replaceFragment();
//drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//drawer.closeDrawer(GravityCompat.START);
return true;
}
public void setTitleOnActionBar(String title) {
getSupportActionBar().setTitle(title);
}
public void setInitialFragment(){
fragment=new TopMainFragment();
FragmentTransaction ft=getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
// ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
drawer.closeDrawer(GravityCompat.START);
}
public void getLoginFragment(){
fragment=new LoginFragment();
FragmentTransaction ft=getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
drawer.closeDrawer(GravityCompat.START);
}
public void replaceFragment(){
FragmentTransaction ft=getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
drawer.closeDrawer(GravityCompat.START);
}
#Override
public void onResume() {
super.onResume();
// Set the title
}
public void getUserObject(User user){
this.user=user;
if(user!=null){
changeLayoutName();
}
}
public void changeLayoutName(){
TextView name= (TextView)layout.findViewById(R.id.textView8);
name.setText(user.getName());
}
}
LoginFragment.java(Fragment)
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.dellpc.reuz_app.Activities.HomeActivity;
import com.example.dellpc.reuz_app.Activities.RegisterActivity;
import com.example.dellpc.reuz_app.Activities.UnableToLoginActivity;
import com.example.dellpc.reuz_app.DTO.User;
import com.example.dellpc.reuz_app.R;
import com.example.dellpc.reuz_app.Validator.IValidation;
import com.example.dellpc.reuz_app.Validator.Validation;
import com.example.dellpc.reuz_app.dao.IUserDAO;
import com.example.dellpc.reuz_app.dao.UserDAO;
public class LoginFragment extends Fragment {
private EditText emailET, passwordET;
private Button loginBTN;
private TextView utlTV, registerTV, invalidEmailTV, invalidPasswordTV;
private View view;
private NavigationView navigationView;
private User user;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// keep the fragment and all its data across screen rotation
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_login, container, false);
Toolbar toolbar = (Toolbar)view.findViewById(R.id.toolbar);
((HomeActivity)getActivity()).getSupportActionBar().setTitle("LOGIN");
this.mapping();
this.listeners(view);
return view;
}
public void mapping(){
emailET = (EditText)view.findViewById(R.id.emailET);
passwordET = (EditText)view.findViewById(R.id.passwordET);
loginBTN = (Button)view.findViewById(R.id.loginBTN);
utlTV = (TextView)view.findViewById(R.id.utlTV);
invalidEmailTV = (TextView)view.findViewById(R.id.invalidEmailTV);
invalidPasswordTV = (TextView)view.findViewById(R.id.invalidPasswordTV);
registerTV = (TextView)view.findViewById(R.id.registerTV);
}
public void listeners(View view){
loginBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = emailET.getText().toString();
String password = passwordET.getText().toString();
validateAndMoveToActivity(email, password);
}
});
utlTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent utlIntent = new Intent(getActivity(), UnableToLoginActivity.class);
startActivity(utlIntent);
}
});
registerTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(getActivity(), RegisterActivity.class);
startActivity(registerIntent);
}
});
emailET.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
invalidEmailTV.setText("");
invalidPasswordTV.setText("");
}
});
passwordET.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s)
{
invalidEmailTV.setText("");
invalidPasswordTV.setText("");
}
});
}
public void validateAndMoveToActivity(String email, String password){
IValidation iValidation = new Validation();
if(!iValidation.isFilled(email) && iValidation.isFilled(password)){
invalidEmailTV.setText("This field is required");
}
else if(iValidation.isFilled(email) && !iValidation.isFilled(password)) {
invalidPasswordTV.setText("This field is required");
}
else if(!iValidation.isFilled(email) && !iValidation.isFilled(password)){
invalidEmailTV.setText("This field is required");
invalidPasswordTV.setText("This field is required");
}
else
{
IUserDAO iUserDAO = new UserDAO(getActivity().getApplicationContext());
/*
if(iUserDAO.isEmailPasswordExist(email, password))*/
if(iUserDAO.isEmailExist(email)){
user=iUserDAO.isEmailPasswordExist(email,password);
if(user!=null)
{
Toast.makeText(view.getContext(), "Successful Login", Toast.LENGTH_SHORT).show();
HomeActivity home=new HomeActivity();
home.getUserObject(user);
/* Intent homeACIntent = new Intent(view.getContext(), HomeActivity.class);
homeACIntent.putExtra("user",user);
startActivity(homeACIntent);*/
// Remove this fragment.
getActivity().getFragmentManager().popBackStack();
}
else {
invalidPasswordTV.setText("Invalid email or password");
}
}
else {
// After successful login where do you want to move your activity.
invalidEmailTV.setText("Invalid phone number or email");
}
}
}
#Override
public void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putSerializable("user",user);
}
}
HomeActivity contains Two Fragments- Login And Top
Initially it shows top fragment
Login Fragment has a option for registration
After successful registration the user is navigated to login fragment
Now after Login the control must reach to the "Top" and the name of the user has to written in the Navigation Drawer
How to do it?
this is my Drawer .t want to write name of User instead of welcome to Reuz
HomeActivity
I see that you're saving the user details in your local database, and then trying to load the data after the user has successfully logged in. The issue that you're facing is that the TextView is not being updated. One possible solution that you can call the changeLayoutName() method from the onViewCreated() method of the TopMainFragment itself.

calling a fragment from fragment

I want to call another fragment from the current fragment on the click of the button in the current fragment.
Here is my Mainactivity :
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.asd.fragments.RecommendationsFragment;
import com.asd.ibitz4college.fragments.SearchCoachingFragment;
import com.asd.fragments.SearchCollegesFragment;
import com.asd.fragments.MainFragment;
import com.asd.fragments.SearchConsultanciesFragment;
import com.asd.fragments.TrendingFragment;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame,new MainFragment()).commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame,new MainFragment()).commit();
if (id == R.id.search_colleges) {
// Handle the Search Colleges action
fm.beginTransaction().replace(R.id.content_frame,new SearchCollegesFragment()).commit();
}
else if (id == R.id.search_consultancies) {
fm.beginTransaction().replace(R.id.content_frame,new SearchConsultanciesFragment()).commit();
}
else if (id == R.id.search_coaching) {
fm.beginTransaction().replace(R.id.content_frame,new SearchCoachingFragment()).commit();
}
else if (id == R.id.my_recommendations) {
fm.beginTransaction().replace(R.id.content_frame, new RecommendationsFragment()).commit();
}
else if (id == R.id.trending) {
fm.beginTransaction().replace(R.id.content_frame, new TrendingFragment()).commit();
} else if (id == R.id.profile) {
} else if (id == R.id.logout) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Here is one of my fragment :
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.asd.k4c.R;
public class SearchCoachingFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.fragment_search_coaching,container,false);
return rootview;
}
} //Update code formatting
Suppose I want to call resultsfragment from the above fragment on the click
of a button whose id is btn_search, then what should I do?
I tried some already existing answers here, no luck!
P.S: I'm a starter to the world of android dev.
For doing a fragment transaction.Please do the following.
Eg..
A and B are fragments.
Currently A is visible to the User. If you want to do a transaction.
Just create as like below
B b = new B();
((YourActivity)getActivity).setnewFragment(b,true);
public void setNewFragment(Fragment fragment,boolean addbackstack) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_content, fragment);
if (addbackstack)
transaction.addToBackStack(title);
transaction.commit();
}
Use an interface to communicate between fragments. For example
public YourFirstFragment extends Fragment {
public interface FragmentCallBack {
void callBack();
}
private FragmentCallBack fragmentCallBack;
public void setFragmentCallBack(FragmentCallBack fragmentCallBack) {
this.fragmentCallBack = fragmentCallBack;
}
private void callThisWhenYouWantToCallTheOtherFragment(){
fragmentCallBack.callBack();
}
}
Then in You activity
private void setCallToFragment{
yourFirstFragment.setFragmentCallBack(new FragmentCallBack(){
void callBack(){
yourSecondFragment.doWhatEver();
}})
}
First you need to create an interface which defines methods that will be used by your fragment to invoke code from the respective activity it is attached to
public interface OnFragmentInteractionlistener {
// the method that you call from your fragment,
// add whatever parameter you need in the implementation of this
// method.
void onClickOfMyView();
}
once you have created the interface, implement it any and all activities that use this fragment.
public class MainActivity extends AppCompatActivity
implements OnMyFragmentInteractionListener {
#Override
public void onClickOfMyView() {
// DO your on click logic here, like starting the transaction
// to add/replace another fragment.
}
}
Then in the onAttach of your fragment to an activity be sure to check if the attaching activity implements this interface, else throw a RunTimeException like so
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnMyFragmentInteractionListener) {
mListener = (OnMyFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnMyFragmentInteractionListener");
}
}
Here mListener is a interface reference you hold in your fragment class through which you invoke the onClickOfMyView() method when actually the click happens
Your fragment class where the view's click code is there.
myView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
mListener.onClickOfMyview();
}
});
You should create some method in your activity. Supposedly it will look like this :
public void startFragment(Fragment fragment) {
fm.beginTransaction().replace(R.id.content_frame,new fragment).commit();
}
As you already done in youronNavigationItemSelected
Then, from your fragment, you can call
((MainActivity)getActivity()).startFragment(new SearchConsultanciesFragment())
for example
Create a method switchFragment in your MainActivity
FragmentTransaction ft;
public void switchFrag() {
try {
ft = getActivity().getFragmentManager().beginTransaction();
ft.replace(R.id.frame_container, new Your_Fragment.class);
ft.commit();
} else {
Log.e("test", "else part fragment ");
}
} catch (Exception e) {
e.printStackTrace();
}
}
Now from your current Fragment you can call this MainActivity's funciton throught the below code:
((MainActivity)getActivity()).switchFrag();
Let me know if this works for you! :)

Fragment OnBackPressed?

I have a doubt i have one activity inside that there are three fragments namely a,b,c transaction will be like a->b->. my doubt is when i enter back button from b it must go to fragment a and frag b should return to its default state how can i achieve it ? am really confused as am new to android i hope you guys are here to help
Here is my Fragment A code:
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import java.util.ArrayList;
public class Leads extends Fragment implements View.OnClickListener {
public Leads(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
ArrayList<NewsItem> listContact = GetlistContact();
ListView lv = (ListView) rootView.findViewById(R.id.listView);
lv.setAdapter(new CustomListAdapter(getActivity(), listContact));
return rootView;
}
private ArrayList<NewsItem> GetlistContact(){
ArrayList<NewsItem> contactlist = new ArrayList<NewsItem>();
NewsItem contact = new NewsItem();
for(int i=1;i<=30;i++) {
contact = new NewsItem();
contact.setHeadline("Yoge " +i);
contact.setReporterName("Yogeshwaran" + i);
contact.setLeadsource("Yogan" + i);
contact.setLeadStatus("open" + i);
contact.setLeadType("Business"+i);
contactlist.add(contact);
}
return contactlist;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Fragment fragment=null;
Button add = (Button) getActivity().findViewById(R.id.btnadd);
add.setOnClickListener(this);
ImageButton filter = (ImageButton) getActivity().findViewById(R.id.btnfilter);
filter.setOnClickListener(this);
}
String str="";
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnadd:
Fragment newFragment = new Add();
str="add";
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.content_frame, newFragment,str);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
}
}
Here is my frag b code:
package first.service.precision.servicefirst;
/**
* Created by 4264 on 23-11-2015.
*/
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by 4264 on 16-10-2015.
*/
public class Add extends Fragment implements View.OnClickListener {
public static ListView lv;
static String sbu, sbuu, sc, ssc, req;
static String bu;
customListAdapterldrequirements customListAdapterldrequirements;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try {
View rootView = inflater.inflate(R.layout.activity_btn_add, container, false);
Spinner ldsource = (Spinner) rootView.findViewById(R.id.lead_source);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
getActivity().getBaseContext(), R.array.dropbox1, R.layout.spinnerlayout);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ldsource.setAdapter(adapter);
// EditText editText=(EditText)rootView.findViewById(R.id.title);
Spinner ldtype = (Spinner) rootView.findViewById(R.id.ldtype);
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(
getActivity().getBaseContext(), R.array.dropbox2, R.layout.spinnerlayout);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ldtype.setAdapter(adapter1);
Spinner ldstatus = (Spinner) rootView.findViewById(R.id.ldstatus);
TextView txt = (TextView) rootView.findViewById(R.id.spinnerTarget);
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
getActivity().getBaseContext(), R.array.dropbox3, R.layout.spinnerlayout);
adapter2.setDropDownViewResource(android.R.layout.simple_selectable_list_item);
ldstatus.setAdapter(adapter2);
// Bundle bundle=getArguments();
// String good=bundle.getString("sbu");
Bundle bundle = getArguments();
// sbu = getArguments().getString("yes");
ArrayList<LdNewsItem> listContact = GetlistContact();
// public boolean onTouch(View v, MotionEvent event) {
// return false;
// }
// Setting on Touch Listener for handling the touch inside ScrollView
//});
lv = (ListView) rootView.findViewById(R.id.ldrequirements);
customListAdapterldrequirements = new customListAdapterldrequirements(getActivity(), listContact);
lv.setAdapter(customListAdapterldrequirements);
// customListAdapterldrequirements customListAdapterldrequirements=new customListAdapterldrequirements(getActivity(),listContact);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
NewRequirements newRequirements = new NewRequirements();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
// lv.deferNotifyDataSetChanged();
ft.replace(R.id.content_frame, newRequirements, "hi");
ft.addToBackStack(null);
ft.commit();
}
});
/* lv.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
// Setting on Touch Listener for handling the touch inside ScrollView
// #Override
// public boolean onTouch(View v, MotionEvent event) {
// Disallow the touch request for parent scroll on touch of child view
// v.getParent().requestDisallowInterceptTouchEvent(true);
//
// return false;
// }
});*/
return rootView;
} catch (Exception e) {
throw e;
}
}
public void updateListView() {
customListAdapterldrequirements.notifyDataSetChanged();
}
private ArrayList<LdNewsItem> GetlistContact() {
ArrayList<LdNewsItem> contactlist = new ArrayList<LdNewsItem>();
// String str=getArguments().getString("yes");
sbu = Main2Activity.sbu;
bu = Main2Activity.bu;
sbuu = Main2Activity.sbuu;
sc = Main2Activity.sc;
ssc = Main2Activity.ssc;
req = Main2Activity.req;
for (int i = 1; i <= 5; i++) {
LdNewsItem contact = new LdNewsItem();
contact.setSbu(sbu);
contact.setBu(bu);
contact.setSbuu(sbuu);
contact.setSc(sc);
contact.setSsc(ssc);
contact.setReq(req);
// contact.setReporterName("No matter how big your house is, how recent your car is, or how big your bank account is — our graves will always be the same size. Stay humble." + i);
contactlist.add(contact);
//lv.setAdapter((ListAdapter) contactlist);
}
return contactlist;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Fragment fragment = null;
setHasOptionsMenu(true);
Button btnrequirements = (Button) getActivity().findViewById(R.id.btnrequirements);
btnrequirements.setOnClickListener(this);
Button btnactnt = (Button) getActivity().findViewById(R.id.btnacnt);
btnactnt.setOnClickListener(this);
Button btnprimary = (Button) getActivity().findViewById(R.id.btnprimary);
btnprimary.setOnClickListener(this);
Button btnsecondary = (Button) getActivity().findViewById(R.id.btnsecondary);
btnsecondary.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnrequirements:
Fragment newFragment = new NewRequirements();
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
break;
case R.id.btnacnt:
FragmentManager fm = getFragmentManager();
//FragmentTransaction ft=fm.beginTransaction();
SelectAccountDialog selectAccountDialog = new SelectAccountDialog();
selectAccountDialog.setRetainInstance(true);
selectAccountDialog.show(fm, "fragment_name");
//ft.addToBackStack(null);
break;
case R.id.btnprimary:
FragmentManager fmm = getFragmentManager();
// FragmentTransaction ftt=fmm.beginTransaction();
SelectAccountDialog selectAccountDialog1 = new SelectAccountDialog();
selectAccountDialog1.setRetainInstance(true);
selectAccountDialog1.show(fmm, "fragment_name");
// ftt.addToBackStack(null);
break;
case R.id.btnsecondary:
FragmentManager fm2 = getFragmentManager();
// FragmentTransaction fttt=fm2.beginTransaction();
SelectAccountDialog selectAccountDialog2 = new SelectAccountDialog();
selectAccountDialog2.setRetainInstance(true);
selectAccountDialog2.show(fm2, "fragment_name");
// fttt.addToBackStack(null);
break;
}
}
/*#Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
Leads leads=new Leads();
FragmentManager back=getFragmentManager();
FragmentTransaction ft=back.beginTransaction();
ft.replace(R.id.content_frame,leads);
ft.addToBackStack(null);
ft.commit();
}*/
}
My activity as below:
package first.service.precision.servicefirst;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class Main2Activity extends Activity {
public static String sbu,bu,sbuu,sc,ssc,req;
// Within which the entire activity is enclosed
private DrawerLayout mDrawerLayout;
// ListView represents Navigation Drawer
private ListView mDrawerList;
Button butonlead;
// ActionBarDrawerToggle indicates the presence of Navigation Drawer in the action bar
private ActionBarDrawerToggle mDrawerToggle;
// Title of the action bar
private String mTitle = "";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
final ActionBar ab = getActionBar();
ab.show();
// Getting reference to the DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ab.setTitle(mTitle);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
// Getting reference to the ActionBarDrawerToggle
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.string.open_drawer,
R.string.close_drawer) {
/** Called when drawer is closed */
public void onDrawerClosed(View view) {
invalidateOptionsMenu();
}
/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
invalidateOptionsMenu();
}
};
// Setting DrawerToggle on DrawerLayout
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Creating an ArrayAdapter to add items to the listview mDrawerList
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplication(),
R.layout.drawer_list_item, R.id.title, getResources().getStringArray(R.array.option));
// Setting the adapter on mDrawerList
mDrawerList.setAdapter(adapter);
// Enabling Home button
ab.setHomeButtonEnabled(true);
ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#53A93F")));
// Enabling Up navigation
ab.show();
ab.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) {
// Getting an array of options
String[] menuItems = getResources().getStringArray(R.array.option);
// Currently selected option
mTitle = menuItems[position];
Fragment fragment = null;
String tag="";
switch (position) {
case 0:
fragment = new Leads();
tag="leads";
break;
case 1:
fragment = new Opportunities();
break;
case 2:
fragment = new Accounts();
break;
case 3:
fragment = new Contactss();
break;
case 4:
fragment = new Documents();
break;
case 5:
fragment = new Reports();
default:
break;
}
if (fragment != null) {
// Getting reference to the FragmentManager
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment,tag).addToBackStack("fragback").commit();
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, fragment);
// Committing the transaction
ft.commit();
// Closing the drawer
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
});
}
#Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
FragmentManager manager = getFragmentManager();
manager.popBackStack();
super.onBackPressed();
}
}
public void changeFragment(Fragment fragment, String tag, boolean shouldAddToBackStack) {
try {
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (shouldAddToBackStack)
ft.addToBackStack(tag);
else {
getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
ft.replace(R.id.content_frame, fragment, tag)
.commit();
getFragmentManager().executePendingTransactions();
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
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);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main2, menu);
return super.onCreateOptionsMenu(menu);
}
/* #Override
public void DataTransfer(String e) {
}*/
//
// #Override
// public void DataTransfer(ArrayList<String> e) {
// Add obj=(Add)getFragmentManager().findFragmentById(R.id.frag_1);
// obj.GetlistContact(e);
// }
}
/* #Override
public void selectedvalue(String s) {
Add add=new Add();
FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.replace(R.id.content_frame,add);
ft.commit();}
}
*/
When you're adding the second fragment to the activity, add the first fragment to back stack:
fragmentTransaction.addToBackStack("fragmentATag");
also override the activity's onBackPressed() method:
#Override
public void onBackPressed() {
FragmentManager manager = getSupportFragmentManager();
if (manager.getBackStackEntryCount() > 0)
manager.popBackStack();
}
write getActivity().getFragmentManager().popBackStack(); in onBackPressedMethod()
You can do this way:
Replace Fragment by below code:
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.content_view, new FragmentB());
ft.addToBackStack(null);
ft.commit();
No need to do code in Fragment B to come back to Fragment A, it will automatically handle, when you press hard back key, if you want to add custom button for coming back from Fragment B to Fragment A than you have to add getActivity.onBackPressed().
Hope this will help you.
There is only one backstack for your application.it is a stack and if we added our fragment to this stack, while pressing back button it will pop out. in your case you can add below code to switch your fragments .put this code both in your main activity as well as parent fragments. pass shouldAddToBackStack as true which fragments you want to add in backstack and it will automatically pop out once you press backbutton
you should replace all this
Fragment newFragment = new NewRequirements();
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
with this function
public void changeFragment(Fragment fragment, String tag, boolean shouldAddToBackStack) {
try {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (shouldAddToBackStack)
ft.addToBackStack(tag);
else {
getActivity().getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
ft.replace(R.id.container, fragment, tag)
.commit();
getActivity().getSupportFragmentManager().executePendingTransactions();
} catch (Exception ex) {
ex.printStackTrace();
}
}

Navigation drawer won't close when item selected

I have a navigation drawer that when an Item is selected, it loads the new fragment but never closes the drawer. My navigation drawer code looks like this:
import android.IntentIntegrator;
import android.IntentResult;
import android.annotation.TargetApi;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
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.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
/**
* Created by Mike and Simon on 2/22/14.
*/
public class MainDrawer2 extends ActionBarActivity
{
private static final String EXTRA_NAV_ITEM = "extraNavItem";
private static final String STATE_CURRENT_NAV = "stateCurrentNav";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavDrawerListAdapter mDrawerAdapter;
private ListView mDrawerList;
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private MainNavItem mCurrentNavItem;
public static Intent createLaunchFragmentIntent(Context context, MainNavItem navItem)
{
return new Intent(context, MainDrawer2.class)
.putExtra(EXTRA_NAV_ITEM, navItem.ordinal());
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
//Crashlytics.start(this);
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerList = (ListView)findViewById(R.id.drawer);
// Set a toolbar to replace the action bar.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitleTextColor(0xFFFFFFFF);
setSupportActionBar(toolbar);
//getActionBar().setDisplayHomeAsUpEnabled(true);
//enableHomeButtonIfRequired();
mDrawerAdapter = new NavDrawerListAdapter(getApplicationContext());
mDrawerList.setAdapter(mDrawerAdapter);
mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
displayNavFragment((MainNavItem)parent.getItemAtPosition(position));
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_menu_white, R.string.app_name, R.string.app_name)
{
public void onDrawerClosed(View view)
{
//getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView)
{
//getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if(getIntent().hasExtra(EXTRA_NAV_ITEM)){
MainNavItem navItem = MainNavItem.values()
[getIntent().getIntExtra(EXTRA_NAV_ITEM,
MainNavItem.STATISTICS.ordinal())];
displayNavFragment(navItem);
}
else if(savedInstanceState != null){
mCurrentNavItem = MainNavItem.values()
[savedInstanceState.getInt(STATE_CURRENT_NAV)];
setCurrentNavItem(mCurrentNavItem);
}
else{
displayNavFragment(MainNavItem.STATISTICS);
}
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void enableHomeButtonIfRequired()
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){
//getActionBar().setHomeButtonEnabled(true);
}
}
public void setActionBarTitle(String title) {
//getActionBar().setTitle(title);
}
#Override
public void setTitle(CharSequence title)
{
mTitle = title;
//getActionBar().setTitle(mTitle);
}
#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);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
if (mCurrentNavItem == null){
}
else{
outState.putInt(STATE_CURRENT_NAV, mCurrentNavItem.ordinal());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/*
#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);
return super.onPrepareOptionsMenu(menu);
}
*/
private void displayNavFragment(MainNavItem navItem)
{
//if(navItem == mCurrentNavItem){
// return;
//}
Fragment fragment = Fragment.instantiate(this,
navItem.getFragClass().getName());
if(fragment != null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.main, fragment)
.commit();
//setCurrentNavItem(navItem);
}
}
private void setCurrentNavItem(MainNavItem navItem)
{
int position = navItem.ordinal();
// If navItem is in DrawerAdapter
if(position >= 0 && position < mDrawerAdapter.getCount()){
//mDrawerList.setItemChecked(position, true);
}
else{
// navItem not in DrawerAdapter, de-select current item
if(mCurrentNavItem != null){
//mDrawerList.setItemChecked(mCurrentNavItem.ordinal(), false);
}
}
//test to keep item not selected
int toClear=mDrawerList.getCheckedItemPosition();
if (toClear >= 0) {
mDrawerList.setItemChecked(toClear, false);
}
mDrawerLayout.closeDrawer(mDrawerList);
//setTitle(navItem.getTitleResId());
mCurrentNavItem = navItem;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
}
else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void goToSearch(MenuItem item){
//go to search page
Fragment Fragment_one;
FragmentManager man= getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new Search();
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
public void scanBarcode(MenuItem item){
//open scanner
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
String scanContent = scanningResult.getContents();
//todo: set scan content into setting, load new fragment which calls async task below. New
//todo: fragment will have same ui as search. :-)
Fragment Fragment_one;
FragmentManager man= this.getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
BarcodeFrag fragmentNew = new BarcodeFrag();
Bundle bundle = new Bundle();
bundle.putString("scanContent", scanContent);
fragmentNew.setArguments(bundle);
tran.replace(R.id.main, fragmentNew);//tran.
tran.addToBackStack(null);
//tran.commit();
tran.commitAllowingStateLoss();
}
else{
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
I also have an enum that I use for my drawer which looks like this:
import android.support.v4.app.Fragment;
public enum MainNavItem
{
// Displayed in NavDrawerListAdapter
STATISTICS("Your Statistics", R.layout.statistics_pagelayout, StatisticsPage.class),
DISCOVER ("Discover", R.layout.activity_discover, BPTopBeers.class),
PORTFOLIO ("Portfolio", R.layout.activity_portfolio, Portfolio.class),
DRINKLOCAL ("Drink Local", R.layout.beer_location_list, DrinkLocal.class),
Map ("Brewery Map", R.layout.activity_brewmap, MapTabs.class),
LISTS ("Your Lists", R.layout.activity_search, AllLists.class),
NEWS ("News", R.layout.activity_news, NewsWeb.class),
Find ("Nearby Breweries", R.layout.beer_location_list, FindBrewery.class),
CONTACT ("Contact", R.layout.activity_contact, ContactPage.class),
// Items NOT displayed in NavDrawerListAdapter
SEARCH ("Search", R.layout.activity_search, Search.class),
;
private static MainNavItem LAST_NAV_ITEM = CONTACT;
private String mTitleResId;
private int mLayoutResId;
private Class<? extends Fragment> mFragClass;
private MainNavItem(String titleResId, int layoutResId, Class<? extends Fragment> fragClass)
{
mTitleResId = titleResId;
mLayoutResId = layoutResId;
mFragClass = fragClass;
}
public int getLayoutResId()
{
return mLayoutResId;
}
public String getTitleResId()
{
return mTitleResId;
}
public Class<? extends Fragment> getFragClass()
{
return mFragClass;
}
public static MainNavItem[] getNavAdapterItems()
{
int count = LAST_NAV_ITEM.ordinal() + 1;
MainNavItem[] adapterItems = new MainNavItem[count];
for(int i = 0; i < count; i++){
adapterItems[i] = values()[i];
}
return adapterItems;
}
}
Add this to your onItemClick method of the mDrawerList
if(mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
}
else {
mDrawerLayout.openDrawer(mDrawerList);
}
I can't find where are you loading fragment in your code but you are probably missing mDrawerToggle.onDrawerClosed(mDrawerLayout); before you replace your fragments.

Categories

Resources