Save Instance for NavigationView? - android

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.

Related

Configure a fragment to be shown first when application is started

I've created a tabbed activity, so many things are already done for me. I followed up a tutorial to, when clicking a drawer item, change to another fragment. Now, I need to, when initializing my app, for my MainFragment to be the default. I actually do not know what's showing up at the moment.
Below's the code of MainActivity that's responsible for handling the fragment change:
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);
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) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
setFragmentTransaction(new MainFragment(), "Dashboard");
break;
case R.id.nav_accounts:
setFragmentTransaction(new AccountFragment(), "Accounts");
break;
case R.id.nav_categories:
break;
case R.id.nav_transactions:
break;
case R.id.nav_reports:
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void setFragmentTransaction(Fragment fragment, String title) {
setTitle(title);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
}
}
I tried setting up a default, but it didn't affect anything.
Add setFragmentTransaction(new MainFragment(), "Dashboard"); to the bottom of onCreate. That should get your main fragment loaded.
You can do like this, you have to load one of your fragment in the onCreate itself so that it can start when app starts.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#BindView(R.id.toolbar)
Toolbar toolbar;
#BindView(R.id.nav_view)
NavigationView navigationView;
#BindView(R.id.drawer_layout)
DrawerLayout drawer;
// tags used to attach the fragments
public static final String TAG_CHAR = "characters";
public static final String TAG_CO = "comics";
public static final String TAG_EV = "events";
public static final String TAG_AB = "about";
public static String CURRENT_TAG = TAG_CHAR;
// index to identify current nav menu item
public static int navItemIndex = 0;
public Fragment fragment;
private Fragment sendFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
if (savedInstanceState != null) {
fragment = getSupportFragmentManager().getFragment(savedInstanceState, "myFragmentName");
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commit();
} else {
navItemIndex = 0;
CURRENT_TAG = TAG_CHAR;
loadHomeFragment();
}
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
}
private void loadHomeFragment() {
selectNavMenu();
if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
drawer.closeDrawers();
return;
} else {
fragment = getHomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commit();
drawer.closeDrawers();
}
}
private Fragment getHomeFragment() {
switch (navItemIndex) {
case 0:
sendFragment = new CharacterFragment();
break;
case 1:
sendFragment = new ComicFragment();
break;
case 2:
sendFragment = new EventFragment();
break;
case 3:
sendFragment = new AboutFragment();
break;
default:
sendFragment = new CharacterFragment();
}
return sendFragment;
}
private void selectNavMenu() {
navigationView.getMenu().getItem(navItemIndex).setChecked(true);
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
return;
}
super.onBackPressed();
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_char:
navItemIndex = 0;
CURRENT_TAG = TAG_CHAR;
break;
case R.id.nav_com:
navItemIndex = 1;
CURRENT_TAG = TAG_CO;
break;
case R.id.nav_ev:
navItemIndex = 2;
CURRENT_TAG = TAG_EV;
break;
case R.id.nav_about_us:
navItemIndex = 3;
CURRENT_TAG = TAG_AB;
break;
default:
navItemIndex = 0;
}
if (menuItem.isChecked()) {
menuItem.setChecked(false);
} else {
menuItem.setChecked(true);
}
menuItem.setChecked(true);
loadHomeFragment();
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "myFragmentName", fragment);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onRestoreInstanceState(savedInstanceState, persistentState);
}
}

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

android navigation drawer recreating fragments everytime

I am loading a simple navigation drawer with 3 fragments inside. When i go to 1st fragment and click a button in that fragment then the buttons background color is changed then i am navigating to second fragment and again i am coming back to the 1st fragment i want my fragment (With color changed button) in the backstack. But it is recreated everytime. I have tried multiple ways no luck. Since i am new to fragments i am stuck with this.
public class SampleActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, Fragment1.OnFragmentInteractionListener,
Fragment2.OnFragmentInteractionListener, Fragment3.OnFragmentInteractionListener {
static Fragment fragment = null;
private static final String FRAGMENT1_TAG = "FRAGMENT1_TAG";
private static final String FRAGMENT2_TAG = "FRAGMENT2_TAG";
private static final String FRAGMENT3_TAG = "FRAGMENT3_TAG";
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
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.dashboard, 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) {
int id = item.getItemId();
navigateToFragment(id);
return true;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
public void navigateToFragment(int itemId) {
// Handle navigation view item clicks here.
String FRAGMENT_TAG="";
switch (itemId) {
case R.id.nav_fragment1:
FRAGMENT_TAG = FRAGMENT1_TAG;
fragment = Fragment1.newInstance();
break;
case R.id.nav_fragment2:
FRAGMENT_TAG = FRAGMENT2_TAG;
fragment = Fragment2.newInstance();
break;
case R.id.nav_fragment3:
FRAGMENT_TAG = FRAGMENT3_TAG;
fragment = Fragment3.newInstance();
break;
default:
FRAGMENT_TAG = FRAGMENT1_TAG;
fragment = Fragment1.newInstance();
break;
}
FragmentManager supportFragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
Fragment inputFragment = supportFragmentManager.findFragmentByTag(FRAGMENT_TAG);
if (inputFragment == null) {
fragmentTransaction.replace(R.id.content_frame, fragment, FRAGMENT_TAG).addToBackStack(null).commit();
} else {
fragmentTransaction.replace(R.id.content_frame, inputFragment, FRAGMENT_TAG).addToBackStack(null).commit();
}
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerLayout.closeDrawer(GravityCompat.START);
}
}
You should add the code of Fragment2.newInstance(); to know better the behaviour.
This code probably solve your problem:
public class SampleActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, Fragment1.OnFragmentInteractionListener,
Fragment2.OnFragmentInteractionListener, Fragment3.OnFragmentInteractionListener {
static Fragment fragment1 = null;
static Fragment fragment2 = null;
static Fragment fragment3 = null;
private static final String FRAGMENT1_TAG = "FRAGMENT1_TAG";
private static final String FRAGMENT2_TAG = "FRAGMENT2_TAG";
private static final String FRAGMENT3_TAG = "FRAGMENT3_TAG";
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
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.dashboard, 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) {
int id = item.getItemId();
navigateToFragment(id);
return true;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
public void navigateToFragment(int itemId) {
// Handle navigation view item clicks here.
String FRAGMENT_TAG="";
Fragment fragment = null;
switch (itemId) {
case R.id.nav_fragment2:
FRAGMENT_TAG = FRAGMENT2_TAG;
if(fragment2 == null) fragment2 = Fragment2.newInstance();
fragment = fragment2;
break;
case R.id.nav_fragment3:
FRAGMENT_TAG = FRAGMENT3_TAG;
if(fragment3 == null) fragment3 = Fragment3.newInstance();
fragment = fragment3;
break;
default:
FRAGMENT_TAG = FRAGMENT1_TAG;
if(fragment1 == null) fragment1 = Fragment1.newInstance();
fragment = fragment1;
break;
}
FragmentManager supportFragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
Fragment inputFragment = supportFragmentManager.findFragmentByTag(FRAGMENT_TAG);
if (inputFragment == null) {
fragmentTransaction.replace(R.id.content_frame, fragment, FRAGMENT_TAG).addToBackStack(null).commit();
} else {
fragmentTransaction.replace(R.id.content_frame, inputFragment, FRAGMENT_TAG).addToBackStack(null).commit();
}
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerLayout.closeDrawer(GravityCompat.START);
}
}
I recommend you to refactor a little bit your code to get a more elegant solution.
Be sure that you're using fragmentTransaction.add() to add a fragment for the first time.
Use stack to keep track on fragment.
Check below link for reference.
https://github.com/rathodchintan/Fragment-Back-Stack
1.do not use replace method if you don't want to reload your fragment.
Instead you it use add method with keeping fragment object in the stack.
if you want to use replace, than check whether fragment is their in the memory by using findFragmentByTag method, and if it's not null use it else create new fragment.

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.

Close Navigation Drawer After Click

How do you close the NavigationDrawer after clicking to open a new Fragment. I have tried a few things but just can't get it to work
MainActivity.java
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, BookAFragment.newInstance())
.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.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 onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_strains) {
Toast.makeText(getApplicationContext(),"Book A Selected", Toast.LENGTH_SHORT).show();
BookAFragment fragment = new BookAFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container,fragment);
fragmentTransaction.commit();
return true;
} else if (id == R.id.nav_recipes) {
Toast.makeText(getApplicationContext(),"Book B Selected", Toast.LENGTH_SHORT).show();
BookBFragment fragment = new BookBFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container,fragment);
fragmentTransaction.commit();
return true;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}

Categories

Resources