How to Update current selected item after backpress in navigation drawer - android

I have successfully implemented navigation drawer but I'm having problems with it.
After selecting fragments and I click the back button, the current fragment pops off and the previous fragment is displayed.
But the title of the displayed fragment is still that of the previous fragment.
Also, the item checked in the drawer is still that of the previous fragment.
Please, do you have any idea how I might update the title and checked item?
My Activity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private final String TAG = "MainActivity";
NavigationView navigationView;
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
String about_blog = "http://example.com/page/json/urls/p-about";
String contri = "http://example.com/page/json/urls/contribute";
String privy = "http://example.com/page/json/urls/privacy-rules";
String contact = "http://example.com/page/json/urls/contact_us";
String advert = "http://example.com/page/json/urls/advertise-here";
String spons = "http://example.com/page/json/urls/sponsor-us";
Fragment fragment = null;
if (id == R.id.menu_home) {
fragment = new PostFragment();
}
if (id == R.id.about_blog) {
fragment = new PageFragment();
} else if (id == R.id.nav_contri) {
fragment = new PageFragment();
} else if (id == R.id.nav_contact) {
fragment = new PageFragment();
} else if (id == R.id.nav_privy) {
fragment = new PageFragment();
} else if (id == R.id.nav_advert) {
fragment = new PageFragment();
} else if (id == R.id.spons) {
fragment = new PageFragment();
} else if (id == R.id.app_about) {
//fragment = new abtFragment();
} else if (id == R.id.settings) {
//fragment = new SettingFragment;
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "Device rotated and onCreate called");
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) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.menu_home);
navigationView.getMenu().performIdentifierAction(R.id.menu_home, 0);
}
UPDATE
I have fixed the issue of updating the title of each fragment after each backpress. What I did was to send the title as a string from MainActivity to the fragment, then in the fragment I receive it and call:
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(title);
This is how my onNavigationItemSelected Code looks like afterwards
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
id = item.getItemId();
Bundle bundle = new Bundle();
String about_blog = "http://example.com/page/json/urls/p-about";
String contri = "http://example.com/page/json/urls/contribute";
String privy = "http://example.com/page/json/urls/privacy-rules";
String contact = "http://example.com/page/json/urls/contact_us";
String advert = "http://example.com/page/json/urls/advertise-here";
String spons = "http://example.com/page/json/urls/sponsor-us";
Fragment fragment = null;
if (id == R.id.menu_home) {
fragment = new PostFragment();
bundle.putString("title", getString(R.string.home));
fragment.setArguments(bundle);
}
if (id == R.id.about_blog) {
bundle.putString("title", getString(R.string.about));
fragment = new PageFragment();
fragment.setArguments(bundle);
} else if (id == R.id.nav_contri) {
bundle.putString("title", getString(R.string.contri));
fragment = new PageFragment();
fragment.setArguments(bundle);
} else if (id == R.id.nav_contact) {
bundle.putString("title", getString(R.string.contac));
fragment = new PageFragment();
fragment.setArguments(bundle);
} else if (id == R.id.nav_privy) {
bundle.putString("title", getString(R.string.privy_p));
fragment = new PageFragment();
fragment.setArguments(bundle);
} else if (id == R.id.nav_advert) {
bundle.putString("title", getString(R.string.advert));
fragment = new PageFragment();
fragment.setArguments(bundle);
} else if (id == R.id.spons) {
bundle.putString("title", getString(R.string.spons));
fragment = new PageFragment();
fragment.setArguments(bundle);
} else if (id == R.id.app_about) {
//fragment = new abtFragment();
} else if (id == R.id.settings) {
//fragment = new SettingFragment;
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment, "visible_fragment");
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
//setTitle(item.getTitle()); // No longer needed.
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
In onCreateView of the fragment I received the String thus:
String title = getArguments().getString("title");
And then still in onCreateView I did:
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(title);
And the title is getting updated now.
The only problem that's is remaining now is the Navigation drawer item that refused to get updated.
And also Android Studio is complaining that method invocation ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(title); mayproduce java.lang.NullPointerException.

You need to set Title for each Fragment Transaction.
Try by Changing on your onNavigationItemSelected like this.
Fragment fragment = null;
String title = "Test";
if (id == R.id.menu_home) {
fragment = new PostFragment();
title = "Post";
}
if (id == R.id.about_blog) {
fragment = new PageFragment();
title = "Page";
} else if (id == R.id.nav_contri) {
fragment = new PageFragment();
title = "Page";
} else if (id == R.id.nav_contact) {
fragment = new PageFragment();
title = "Page";
} else if (id == R.id.nav_privy) {
fragment = new PageFragment();
title = "Page";
} else if (id == R.id.nav_advert) {
fragment = new PageFragment();
title = "Page";
} else if (id == R.id.spons) {
fragment = new PageFragment();
title = "Page";
} else if (id == R.id.app_about) {
//fragment = new abtFragment();
} else if (id == R.id.settings) {
//fragment = new SettingFragment;
}
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
**// set the toolbar title
getSupportActionBar().setTitle(title);**
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
EDIT 1:
OverRide onResume of your MainActivity.
Using this Code.
#Override
public void onResume() {
super.onResume();
// Set title
getActivity().getActionBar()
.setTitle("Your Title Goes Here");
}

You can also do like this.
#Override
public void onBackPressed() {
super.onBackPressed();
getSupportActionBar().setTitle(getResources().getString(R.string.titlefragment));
}

Related

Change Fragment Layout (RTL , LTR) on runtime when changing language

i am using a Drawer Navigation activity to handle fragments , and i have an options menu to change Locale like this :
public class DrawerNavigationActivity extends AppCompatActivity implements NavigationView
.OnNavigationItemSelectedListener, AgendaMainFragment.OnFragmentInteractionListener,
MediaMainFragment.OnFragmentInteractionListener, VideosFragment
.OnFragmentInteractionListener, PhotosFragment.OnFragmentInteractionListener,
ThemesMainFragment.OnFragmentInteractionListener, AdresseMainFragment
.OnFragmentInteractionListener, InfoMainFragment.OnFragmentInteractionListener,
NewsMainFragment.OnFragmentInteractionListener, BlockMainFragment
.OnFragmentInteractionListener, DemosMainFragment.OnFragmentInteractionListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer_navigation);
setTitle(R.string.app_name);
//########################################################### set initial fragment
Bundle b = getIntent().getExtras();
Fragment fragment = null;
if(b.getInt("link") == 1) {
fragment = new AgendaMainFragment();
}else if(b.getInt("link") == 2){
fragment = new MediaMainFragment();
}else if(b.getInt("link") == 3){
fragment = new ThemesMainFragment();
}else if(b.getInt("link") == 4){
fragment = new AdresseMainFragment();
}else if(b.getInt("link") == 5){
fragment = new InfoMainFragment();
}else if(b.getInt("link") == 6){
fragment = new NewsMainFragment();
}else if(b.getInt("link") == 7){
fragment = new BlockMainFragment();
}else if(b.getInt("link") == 8){
fragment = new DemosMainFragment();
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.frag_drawer_container, fragment);
ft.commit();
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#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.drawer_navigation, 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();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
switch (id) {
case R.id.fr:
LocaleHelper.setLocale(getBaseContext(), "fr");
LocaleHelper.updateGlobalConfig(getBaseContext());
ft.detach(getVisibleFragment()).attach(getVisibleFragment()).commit();
return true;
case R.id.ar:
LocaleHelper.setLocale(getBaseContext(), "ar");
LocaleHelper.updateGlobalConfig(getBaseContext());
ft.detach(getVisibleFragment()).attach(getVisibleFragment()).commit();
return true;
case R.id.en:
LocaleHelper.setLocale(getBaseContext(), "en");
LocaleHelper.updateGlobalConfig(getBaseContext());
ft.detach(getVisibleFragment()).attach(getVisibleFragment()).commit();
return true;
case R.id.es:
LocaleHelper.setLocale(getBaseContext(), "es");
LocaleHelper.updateGlobalConfig(getBaseContext());
ft.detach(getVisibleFragment()).attach(getVisibleFragment()).commit();
return true;
}
return super.onOptionsItemSelected(item);
}
public Fragment getVisibleFragment(){
FragmentManager fragmentManager = DrawerNavigationActivity.this.getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
if(fragments != null){
for(Fragment fragment : fragments){
if(fragment != null && fragment.isVisible())
return fragment;
}
}
return null;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Fragment fragment = null;
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
super.onBackPressed();
return true;
} else if(id == R.id.nav_agenda) {
fragment = new AgendaMainFragment();
} else if (id == R.id.nav_gallery) {
fragment = new MediaMainFragment();
} else if (id == R.id.nav_themes) {
fragment = new ThemesMainFragment();
} else if (id == R.id.nav_adresse) {
fragment = new AdresseMainFragment();
}else if (id == R.id.nav_info) {
fragment = new InfoMainFragment();
}else if (id == R.id.nav_news) {
fragment = new NewsMainFragment();
}else if (id == R.id.nav_blocs) {
fragment = new BlockMainFragment();
}else if (id == R.id.nav_demo_animation) {
fragment = new DemosMainFragment();
}else{
return true;
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.frag_drawer_container,fragment);
ft.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onAgendaFragmentInteraction(Uri uri) {
}
#Override
public void onMediaFragmentInteraction(Uri uri) {
}
#Override
public void onFragmentInteraction(Uri uri) {
}
#Override
public void onFragmentPhotoInteraction(Uri uri) {
}
for my fragments i change the bar action title like this :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_news_main, container, false);
LocaleHelper.updateGlobalConfig(getContext());
getActivity().setTitle(getResources().getString(R.string.fgmt_titre_news));
return view;
}
it's working fin except for an RTL language , when i choose and RTL locale it change the title and the content but keeps the layout orientation LTR , so if i close the application and reopen again it changes the oriontation to RTL but keeps it even for LTR fragments:
by orientation i mean the action bar and the drawer navigation.
Fragment with local Fr :
Change Local to AR (RTL)
close the App and reopen it and navigate to RTL fragment
navigate to another LTR fragment (it keeps RTL Layout Orientation)
what am i doing wrong and what is the best and clean way to achieve it ?

Back Handling in Fragment While Using Navigation DrawerLayout

I am getting Problem in Navigation drawer if I am clicking any drawer item more than one time (Example 5 times) then on back press I am getting 5 time same fragment.
Suppose first I had click on Fragment one then 5 times on fragment two then after on Back Handling or on Back Pressed first 5 times second fragment has been called and the the fragment one.
I want that if the same no. of fragment I have clicked multiple times the no need to push it on stack.
How to handle this?
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,HomeListFragment.MyListFragmentListener {
private Stack<Fragment> fragmentStack;
private FragmentManager fragmentManager;
private HomeListFragment homeListFragment;
private ResultListFragment resultListFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/* FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});*/
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);
fragmentStack = new Stack<Fragment>();
homeListFragment = new HomeListFragment();
homeListFragment.registerForListener(this);
fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.add(R.id.container, homeListFragment);
fragmentStack.push(homeListFragment);
ft.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
if (fragmentStack.size() >1) {
FragmentTransaction ft = fragmentManager.beginTransaction();
fragmentStack.lastElement().onPause();
ft.remove(fragmentStack.pop());
fragmentStack.lastElement().onResume();
ft.show(fragmentStack.lastElement());
ft.commit();
} 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);
}
#Override
public void onItemClickedListener(String valueClicked) {
Toast.makeText(this, valueClicked, Toast.LENGTH_LONG).show();
FragmentTransaction ft = fragmentManager.beginTransaction();
resultListFragment = new ResultListFragment();
ft.add(R.id.container, resultListFragment);
fragmentStack.lastElement().onPause();
ft.hide(fragmentStack.lastElement());
fragmentStack.push(resultListFragment);
ft.commit();
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
FragmentTransaction ft = fragmentManager.beginTransaction();
One one = new One();
ft.replace(R.id.container, one,"One");
fragmentStack.lastElement().onPause();
ft.hide(fragmentStack.lastElement());
fragmentStack.push(one);
ft.commit();
} else if (id == R.id.nav_gallery) {
FragmentTransaction ft = fragmentManager.beginTransaction();
Two two = new Two();
ft.replace(R.id.container, two,"Two");
fragmentStack.lastElement().onPause();
ft.hide(fragmentStack.lastElement());
fragmentStack.push(two);
ft.commit();
} else if (id == R.id.nav_slideshow) {
FragmentTransaction ft = fragmentManager.beginTransaction();
Three three = new Three();
ft.replace(R.id.container, three,"Three");
fragmentStack.lastElement().onPause();
ft.hide(fragmentStack.lastElement());
fragmentStack.push(three);
ft.commit();
} else if (id == R.id.nav_manage) {
FragmentTransaction ft = fragmentManager.beginTransaction();
Four four = new Four();
ft.replace(R.id.container, four,"Four");
fragmentStack.lastElement().onPause();
ft.hide(fragmentStack.lastElement());
fragmentStack.push(four);
ft.commit();
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Please Help
//You are using backstack to hold the previous fragments remove all the fragment stacks
One one = new One();
ft.replace(R.id.container, one,"One");
ft.commit();
or you may use below code in backPress method
getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
You can simply check the current fragment instance is exist or not by tag. Check the fragment is exist or not and then do your logic by that.
Fragment fragment = getFragmentManager().findFragmentByTag("yourstringtag");
if (fragment instanceof yourFragment) {
// No need to commit new one
} else {
// Commit new one
}
Another simple method to solve this issue by using a currentFragment instance. Please consider this as an example logic, I didn't checked it.
private Fragment mFragment;
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
if (!(mFragment instanceof One)) {
FragmentTransaction ft = fragmentManager.beginTransaction();
One one = new One();
ft.replace(R.id.container, one, "One");
fragmentStack.lastElement().onPause();
ft.hide(fragmentStack.lastElement());
fragmentStack.push(one);
mFragment = one;
ft.commit();
}
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}

setRetainInstance not working

I'm using a navigatin drawer to switch betwen two fragments. I use setRetainInstance(true) in both fragments, but it's not working. In FeedFragment there is a simple textView and in the MapFragment there is a google map.
FeedFragment and MapFragment (same code inside onCreate)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
MainActivity
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
Fragment fragment = null;
if (id == R.id.nav_feed) {
if (feedFragment == null)
feedFragment = new FeedFragment();
fragment = feedFragment;
} else if (id == R.id.nav_mapa) {
if (mapFragment == null)
mapFragment = new MapFragment();
fragment = mapFragment;
}
try {
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
} catch (Exception e) {
e.printStackTrace();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
EDIT
I found a solution. I change the fragment in the replace function to feedFragment, or mapFragment.
if (id == R.id.nav_feed) {
if (feedFragment == null)
feedFragment = new FeedFragment();
fragmentManager.beginTransaction().replace(R.id.content_frame, feedFragment).commit();
} else if (id == R.id.nav_mapa) {
if (mapFragment == null)
mapFragment = new MapFragment();
fragmentManager.beginTransaction().replace(R.id.content_frame, mapFragment).commit();
}

Blank page after selecting a default item and pressing back button NavigationView

I am selecting a default fragment in NavigationView when my activity starts up,
it works alright but the problem with it is that when I press the back button, I see a blank view.
My Activity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private final String TAG = "MainActivity";
NavigationView navigationView;
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
String about_blog = "http://example.com/page/json/urls/p-about";
String contri = "http://example.com/page/json/urls/contribute";
String privy = "http://example.com/page/json/urls/privacy-rules";
String contact = "http://example.com/page/json/urls/contact_us";
String advert = "http://example.com/page/json/urls/advertise-here";
String spons = "http://example.com/page/json/urls/sponsor-us";
Fragment fragment = null;
if (id == R.id.menu_home) {
fragment = new PostFragment();
}
if (id == R.id.about_blog) {
fragment = new PageFragment();
} else if (id == R.id.nav_contri) {
fragment = new PageFragment();
} else if (id == R.id.nav_contact) {
fragment = new PageFragment();
} else if (id == R.id.nav_privy) {
fragment = new PageFragment();
} else if (id == R.id.nav_advert) {
fragment = new PageFragment();
} else if (id == R.id.spons) {
fragment = new PageFragment();
} else if (id == R.id.app_about) {
//fragment = new abtFragment();
} else if (id == R.id.settings) {
//fragment = new SettingFragment;
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "Device rotated and onCreate called");
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) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.menu_home);
navigationView.getMenu().performIdentifierAction(R.id.menu_home, 0);
}
To expatiate, when I launch the app, PostFragment is launched by default. When I click the back key, instead of the app closing, I meet a blank page.
Please, what am I doing wrong here and how do I correct it?
I have found the solution here. Just paste this
FragmentManager fm = getSupportFragmentManager();
fm.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override public void onBackStackChanged() { if (getSupportFragmentManager().getBackStackEntryCount() == 0) finish(); } });
In the hosting activity's onCreate.
What this does is to finish the activity if the current fragment is the last in the back stack.

How to use the Navigation Drawer to switch Activities[Android Studio]

I created an Navigation Drawer Activity in Android Studio 1.4. My Main Activity is already setted up and now I want to switch to another Activity via the Navigation Drawer. The second Activity (AddDataActivity) should collect some User Unputs to create string which should be displayed in my Main Activities ListView.
My problem is, that I dont know how to open the AddDataActivity without "loosing" my navigation Drawer.
Intent AddData = new Intent(MainActivity.this, AddDataActivity.class);
MainActivity.this.startActivity(AddData);
Do I have to copy the whole Drawer Code for each Activity? Or would it be better to use Fragments?
I use Fragments now I avoid this Situation.
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Fragment fragment;
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
fragment = new ListViewFragment();
int id = item.getItemId();
if (id == R.id.nav_listview) {
fragment= new ListViewFragment();
} else if (id == R.id.nav_add_data) {
fragment= new AddDataFragment();
} else if (id == R.id.nav_settings) {
fragment= new SettingsFragment();
} else if (id == R.id.nav_rooms) {
fragment= new SavedRoomsFragment();
} else if (id == R.id.nav_legal_information) {
fragment = new LegalInformationFragment();
}
ft.replace(R.id.container, fragment);
ft.addToBackStack(null);
ft.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}

Categories

Resources