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

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.

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 ?

Navigation Drawer open close pane not working with smoothness

This is my gif of problem. I am using navigation drawer, and I have done some code as per below but the pane close and open is not working with require smoothness.
This is my code:
public class SettingFlyout extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
SharedPreferences pref;
SharedPreferences.Editor editor;
public DrawerLayout drawer;
public ActionBarDrawerToggle toggle;
public NavigationView navigationView;
LinearLayout viewPager;
int roleId;
FragmentStack fragmentStack = FragmentStack.getInstance();
#Override
public void onPanelClosed(int featureId, Menu menu) {
super.onPanelClosed(featureId, menu);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting_flyout);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TextView credits, num_credits, ttlscore, num_ttlscore, tutorNow;
final Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/GothamBookRegular.ttf");
View v = getLayoutInflater().inflate(R.layout.student_actionbar_view, null);
credits = (TextView) v.findViewById(R.id.credits);
credits.setTypeface(typeface);
viewPager = (LinearLayout) findViewById(R.id.viewpager);
Intent i = getIntent();
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
int status = i.getIntExtra("status", 1);
String username = i.getStringExtra("username");
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setItemIconTintList(null);
View view = navigationView.getHeaderView(0);
TextView TVuserName = (TextView) view.findViewById(R.id.personTextsettingflyout);
TVuserName.setText(username);
if (status == 0) {
roleId = Integer.parseInt(i.getStringExtra("roleId"));
}
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
Tablayout_with_viewpager withViewpager = new Tablayout_with_viewpager(status, roleId);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.viewpager, withViewpager);
fragmentTransaction.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
FragmentManager fragmentManager = getSupportFragmentManager();
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else
if (fragmentStack.size()==0) {
super.onBackPressed();
finish();
moveTaskToBack(true);
} else if (fragmentStack.size()>0) {
if (fragmentStack.size()<2 || fragmentStack.size()==2 || fragmentStack.isEmpty()){
super.onBackPressed();
finish();
moveTaskToBack(true);
SplashScreen splashScreen=new SplashScreen();
splashScreen.onBackPressed();
} else {
Fragment fragment = fragmentStack.pop();
if (fragment.getClass().equals(""))
Toast.makeText(getApplicationContext(), fragment.getClass().toString(), Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), String.valueOf(fragmentStack.size()), Toast.LENGTH_SHORT).show();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.viewpager, fragment).commit();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragment;
if (id == R.id.profile) {
Tablayout_with_viewpager tablayout_with_viewpager = new Tablayout_with_viewpager();
fragmentTransaction.replace(R.id.viewpager, tablayout_with_viewpager).commit();
// Handle the camera action
} else if (id == R.id.desired_tutor) {
DesiredTutor desiredTutor = new DesiredTutor();
fragmentTransaction.replace(R.id.viewpager, desiredTutor).commit();
} else if (id == R.id.payment_options) {
BuyCredits buyCredits=new BuyCredits();
fragmentTransaction.replace(R.id.viewpager, buyCredits).commit();
} else if (id == R.id.lesson_tracking) {
lessonTracking lessonTracking=new lessonTracking();
fragmentTransaction.replace(R.id.viewpager, lessonTracking).commit();
} else if (id == R.id.TTL_Score) {
TTL_Score ttl_score = new TTL_Score();
fragmentTransaction.replace(R.id.viewpager, ttl_score).commit();
} else if (id == R.id.History) {
History history = new History();
fragmentTransaction.replace(R.id.viewpager, history).commit();
} else if (id == R.id.notification) {
Notification notification = new Notification();
fragmentTransaction.replace(R.id.viewpager, notification).commit();
} else if (id == R.id.support) {
Support support = new Support();
fragmentTransaction.replace(R.id.viewpager, support).commit();
} else if (id == R.id.sign_out) {
pref=getSharedPreferences("loginStatus", Context.MODE_PRIVATE);
editor=pref.edit();
editor.clear();
editor.apply();
Intent i = new Intent(getApplicationContext(), Login.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
else if (id== R.id.daily_game){
TutorGuides dailyGame= new TutorGuides();
fragmentTransaction.replace(R.id.viewpager, dailyGame).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
what should I do to make it smoother?
Every time used this code it not need to use this code every time define in once a time:-
fragmentTransaction.replace(R.id.viewpager, desiredTutor).commit();
Create a method:-
public static void showFragment(Fragment fragment, String Tag) {
FragmentManager manager = activity.getSupportFragmentManager();
FragmentTransaction transcation = manager.beginTransaction();
transcation.replace(R.id.viewpager, fragment, Tag);
transcation.addToBackStack(Tag);
transcation.commit();
}
and use this :-
switch (item.getItemId())
{
case R.id.desired_tutor:
showFragment(new DesiredTutor(), "");
break;
case R.id.payment_options:
showFragment(new BuyCredits(), "");
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
You are initiating it everytime. Its wrong. Just initialize it once and use that object to open and close the drawer. remove that code from item selected listener and put it in to Oncreate to initialize it once.
Use below code to make it perfect :
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
toggle.syncState();
}
ActionBarDrawerToggle toggle;
toggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(toggle);

Other Fragment is viewed above the current fragment changes on rotation with android studio navigation drawer template

Thank you for spending time on my qeustion. In my app I am using android studio navigation drawer template.
But the problem is that, when I rotate the phone, the previous fragment's layout is shown above the current fragment.
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);
Fragment fragment = null;
Class fragmentClass = null;
/* if (savedInstanceState == null){
try{
fragment = (Fragment) fragmentClass.newInstance();
}catch (Exception e){
e.printStackTrace();
}
}*/
fragment = new Login();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.fragment, fragment);
fragmentTransaction.commit();
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);
}
#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();
Fragment fragment =null ;
Class fragmentClas = null;
if (id == R.id.nav_camera) {
// Handle the camera action
fragment = new Attendance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_gallery) {
fragment = new AddStudent();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
/* 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;
}
}
When you rotate the device, the activity saves its current state and keeps the current fragment then it's destroyed and recreated i.e. onCreate() is called again. You had one fragment before it's destroyed and now it added another in the new call to onCreate() that's why you have 2 fragments. To fix this you should check first if the savedInstanceState parameter in onCreate() is null i.e. it's the first creation of activity not just being restarted due to rotation change or anything, then decide to add the fragment or not instead of adding to whenever the activity calls onCreate()
if(savedInstanceState == null) {
// Add the fragment because it's normal creation
fragment = new Login();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.fragment, fragment);
fragmentTransaction.commit();
}

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

Save Instance for NavigationView?

I am using the
Navigation Drawer Activity
that build in android studio when creating new project
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Toolbar toolbar;
NavigationView navigationView;
DrawerLayout drawerLayout;
private static final String PREFERENCES_FILE = "mymaterialapp_settings";
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
private int mCurrentSelectedPosition;
private MenuBuilder mMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("main");
setSupportActionBar(toolbar);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
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);
Fragment squadFragment = new MainItems();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.contaner,squadFragment,null);
fragmentTransaction.commit();
mCurrentSelectedPosition=0;
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
Fragment fragment = null;
String name;
if (id == R.id.nav_camera) {
Fragment f=new MainItems();
fragmentTransaction.replace(R.id.contaner,f);
fragmentTransaction.commit();
name="Main";
mCurrentSelectedPosition=1;
toolbar.setTitle(name);
} else if (id == R.id.nav_docaans) {
Fragment f =Docaans.newInstance("key1");
fragmentTransaction.replace(R.id.contaner,f);
fragmentTransaction.commit();
name="page 2";
mCurrentSelectedPosition=2;
toolbar.setTitle(name);
} else if (id == R.id.nav_friday) {
Fragment f=new MainFragment();
fragmentTransaction.replace(R.id.contaner,f);
fragmentTransaction.commit();
mCurrentSelectedPosition=3;
name="page 4";
toolbar.setTitle(name);
} else if (id == R.id.nav_cat) {
Fragment f=new Catalogat();
fragmentTransaction.replace(R.id.contaner,f);
fragmentTransaction.commit();
mCurrentSelectedPosition=4;
name="page n";
toolbar.setTitle(name);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION, 0);
Menu menu = navigationView.getMenu();
menu.getItem(mCurrentSelectedPosition).setChecked(true);
}
}
as shown in code snip i am use number of fragments when i use one item from the navigation item it replace the current fragment
but when i am rotate the screen it start the main screen and i need to save instance for my fragment
How Can I do this ?
Your logic to save the instance state is pretty much correct. You just need to restore it in OnCreate method of your Activtity.
You can do it like so -
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
//Here you can use an if else block to inflate the desired fragment
if (mCurrentSelectedPosition == R.id.nav_camera) {
//ADD THE FRAGMENT YOU WANT HERE...
} else if (mCurrentSelectedPosition == R.id.nav_docaans) {
//REPLACE THE FRAGMENT HERE ...
} else if (mCurrentSelectedPosition == R.id.nav_friday) {
//DO WHAT YOU WANT HERE
} else if (mCurrentSelectedPositon == R.id.nav_cat) {
//YOUR LOGIC HERE AGAIN
}
}
Let me know if this works.

Categories

Resources