setRetainInstance not working - android

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

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 ?

How to handle onBackPressed() in multiple fragment

I am Android beginner, I am developing an app in which I have used multiple fragments through an activity.
private void displaySelectedScreen(int itemId) {
Fragment fragment = null;
switch (itemId) {
case R.id.nav_home:
fragment = new HomeFragment();
break;
case R.id.nav_attendance:
fragment = new AttendanceFragment();
break;
case R.id.nav_notification:
fragment = new NotificationFragment();
break;
case R.id.nav_event:
fragment = new EventFragment();
break;
case R.id.nav_fee:
fragment = new FeesFragment();
break;
case R.id.nav_news:
fragment = new NewsFragment();
break;
}
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.frame_container, fragment);
ft.addToBackStack(null);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
and use an onBackPressed() method to close an app if the drawer is already close. Now I want to close an app if current fragment is HomeFragment and if current fragment is not HomeFragment then replace by HomeFragment. I don't know, how it does?
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
closeApp();
}
}
You can add tag to your fragment. in this way you will only have to check the tag name.
Fragment fragment = new Fragment();
getFragmentManager().beginTransaction()
.replace(R.id.FrameLayoutId,fragment,"TAG_NAME")
.addToBackStack("SOURCE_TAG_NAME").commit();
This is how to check your fragment tag, put this checking on your backpress method on the activity or in your closeApp() method
function void closeApp(){
Fragment fragment = getFragmentManager().findFragmentByTag("HomeActivity");
if (fragment != null) {
if(fragment.isVisible()){
HomeActivity.this.finish();
}
}
}
Use this code onBackPressed() method in NavigationActivity. I hope that can solve you.
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
Fragment f = getVisibleFragment();// to get which fragment now
if (f.getClass() != MainFragment.class) {
Fragment fragment = null;
try {
fragment = (Fragment) MainFragment.class.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame, fragment).commit(); // this is your framelayout
}else {
super.onBackPressed();
}
}
}
getVisibleFragment() function
public Fragment getVisibleFragment() {
FragmentManager fragmentManager = NavigationActivity.this.getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
if (fragment != null && fragment.isVisible())
return fragment;
}
}
return null;
}
For simple, just go to your HomeFragment.java and edit the method onBackPressed() to exit the application using finish().
And for others Fragment.java, just use popBackStack() function, you can search for it here :
https://developer.android.com/reference/android/app/FragmentManager.html#popBackStack()
In your MainActivity class override onBackPressed and display dialogbox there like this:
#Override
public void onBackPressed() {
//show dialog box here
}
In each Fragment implement onResume() method with following code:
#Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
//homefragment class name
Class fragmentClass = HomeFragment.class;
try {
Fragment fragment = (Fragment) fragmentClass.newInstance();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
return false;
}
});
}

Full-screen fragment to fragment transition displayed main activity during fragment transition

In my android application, I had one main activity(i.e.Home) and two full-screen fragments. I can access theses three using Navigation Drawer. These two fragments act as the separate screen but actually its top on main activity.
In my case, I clicked the first fragment then I clicked the second fragment. During this time, I closed the first fragment and displayed the second fragment. But, main activity screen was now displayed one second during fragment transition.
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_in, R.anim.slide_out);
if(!item.isChecked())
getSupportFragmentManager().popBackStackImmediate(null, POP_BACK_STACK_INCLUSIVE);
item.setChecked(true);
if (previousMenuItem != item.getItemId()) {
if (item.getItemId() == R.id.fragment_two) {
initialiseFragmentTwo();
} else if (item.getItemId() == R.id.nav_main_activity) {
getSupportFragmentManager(). popBackStackImmediate(null, POP_BACK_STACK_INCLUSIVE);
getSupportActionBar().setTitle(R.string.app_name);
}
else if(item.getItemId() == R.id.nav_fragment_one){
initialiseFragmentOne();
}
}
previousMenuItem = item.getItemId();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer != null) {
drawer.closeDrawer(GravityCompat.START);
}
return true;
}
Instead of using POP_BACK_STACK_INCLUSIVE try to use replace
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment = null;
Class fragmentClass = null;
if (id == R.id.nav_camera) {
fragmentClass = FragmentOne.class;
} else if (id == R.id.nav_gallery) {
fragmentClass = FragmentTwo.class;
} else if (id == R.id.nav_slideshow) {
fragmentClass = FragmentOne.class;
} else if (id == R.id.nav_manage) {
fragmentClass = FragmentTwo.class;
} else if (id == R.id.nav_share) {
fragmentClass = FragmentOne.class;
} else if (id == R.id.nav_send) {
fragmentClass = FragmentTwo.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
See here below links
http://chrisrisner.com/Using-Fragments-with-the-Navigation-Drawer-Activity
https://www.simplifiedcoding.net/android-navigation-drawer-example-using-fragments/

Switch back to SupportMapFragment is displaying a blank activity

I have a problem of SuportMap fragment, while it's displaying a blank fragment when I switch back to the Map fragment, and this is the situation:
I have Main activity with left drawer, the drawer contains tow items to display fragment A and fragment B, Fragment A containing tab host with 2 tabs (map tab and second Tab).
the application is displaying the Map on lunching, and it's ok, but if I select the second item in the drawer to go to the fragment B, and back to fragment A, the Map fragment is displaying a blank fragment, and if I select another tab and back to the map tab then it displaying the map again successfully. and I do not know what is the wrong.
MainActivity:
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
MainFragment mainFragment = (MainFragment) getSupportFragmentManager().findFragmentByTag(MainFragment.TAG);
if (id == R.id.nav_home && mainFragment == null) {
showFragment(new MapFragment(), "MapFragment");
} else if (id == R.id.nav_gallery &&
getSupportFragmentManager().findFragmentByTag(GalleryFragment.TAG) == null) {
showFragment(new B(), "B");
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
assert drawer != null;
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void showFragment(Fragment fragment, String tag) {
FragmentManager manager = getSupportFragmentManager();
boolean fragmentPopped = manager.popBackStackImmediate(tag, 0);
if (!fragmentPopped) { //fragment not in back stack, create it.
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.content, fragment);
ft.addToBackStack(tag);
ft.commit();
}
}
Fragment A:
private void initTabHost() {
mTHost.setOnTabChangedListener(this);
mTHost.setup();
TabHost.TabSpec MapSpec = mTHost.newTabSpec(PeopleFragment.TAG);
MapSpec.setIndicator(getTabIndicator(R.string.tool_bar_people, R.drawable.selector_map_tab));
MapSpec.setContent(new DummyTabContent(getActivity()));
mTHost.addTab(MapSpec);
TabHost.TabSpec secondSpec = mTHost.newTabSpec(SecondFragment.TAG);
secondSpec.setIndicator(getTabIndicator(R.string.tool_bar_news, R.drawable.selector_second_tab));
secondSpec.setContent(new DummyTabContent(getActivity()));
mTHost.addTab(secondSpec);
}
private View getTabIndicator(int title, int icon) {
View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_tab_layout, null);
ImageView ivIcon = (ImageView) view.findViewById(R.id.iv_icon);
ivIcon.setImageResource(icon);
TextView tvTitle = (TextView) view.findViewById(R.id.tv_title);
tvTitle.setText(title);
return view;
}
#Override
public void onTabChanged(String tabId) {
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MapFragment mapFragment = (MapFragment) fragmentManager.findFragmentByTag(MapFragment.TAG);
SecondFragment secondFragment = (SecondFragment) fragmentManager.findFragmentByTag(SecondFragment.TAG);
if (mapFragment != null) {
fragmentTransaction.detach(mapFragment);
}
if (secondFragment != null) {
fragmentTransaction.detach(secondFragment);
}
if (tabId.equalsIgnoreCase(MapFragment.TAG)) {
if (mapFragment == null) {
fragmentTransaction.add(R.id.fl_real_tab_content, new MapFragment(), MapFragment.TAG);
} else {
fragmentTransaction.attach(mapFragment);
}
} else if (tabId.equalsIgnoreCase(SecondFragment.TAG)) {
if (secondFragment == null) {
fragmentTransaction.add(R.id.fl_real_tab_content, new SecondFragment(), SecondFragment.TAG);
} else {
fragmentTransaction.attach(SecondFragment);
}
}
fragmentTransaction.commit();
}
MapFragment:
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
}
public void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the mMap.
((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map))
.getMapAsync(this);
}
Any help what Should I do and what is the problem?
I have fixed this issue in a work around solution, through add android:launchMode=="SingleInstance" to the activity in the manifests file.
in this case when we go back to the activity, then the activity will not create new fragments and reset the states from first.

How to Update current selected item after backpress in navigation drawer

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

Categories

Resources