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);
}
}
Related
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);
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.
I'm building an app which contains a NavigationDrawer to navigate between Fragments.
For some reason, when pressing on any item in the Navigation Drawer the item just marks itself and doesn't change the fragment (tried debug but the item clicks doesn't calls the functions)
The fragment is not loading in first click..i have to press twice to reload the fragment
Main Activity:
public class MainActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawer;
private View navHeader;
private ImageView imgNavHeaderBg, imgProfile;
private TextView txtName, txtCity;
private Toolbar toolbar;
private FloatingActionButton fab;
// urls to load user profile & background
private static final String urlNavHeaderBg = "";
private static final String urlProfileImg = "";
//current menu pressed
public static int navItemIndex = 0;
//tags for fragments
private static final String TAG_HOME = "home";
private static final String TAG_PROFILE = "profile";
private static final String TAG_RATEUS = "rate us";
private static final String TAG_SCORE = "rate score";
private static final String TAG_NOTIFICATIONS = "notifications";
private static final String TAG_SETTINGS = "settings";
public static String CURRENT_TAG = TAG_HOME;
private String[] activityTitles;
private boolean shouldLoadHomeFragOnBackPress = true;
private Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mHandler = new Handler();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
fab = (FloatingActionButton) findViewById(R.id.fab);
//nav view header
navHeader = navigationView.getHeaderView(0);
txtName = (TextView) navHeader.findViewById(R.id.name);
txtCity = (TextView) navHeader.findViewById(R.id.city);
imgNavHeaderBg = (ImageView) navHeader.findViewById(R.id.img_header_bg);
imgProfile = (ImageView) navHeader.findViewById(R.id.img_profile);
//load the toolbar titles
activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Make action here", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
});
//load the navigator header data
loadNavHeader();
//initialize nav menu
setUpNavigationView();
if (savedInstanceState == null) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
}
}
private void loadNavHeader() {
txtName.setText("My Name");
txtCity.setText("Somewhere, Europe");
Glide.with(this).load(urlNavHeaderBg).crossFade().diskCacheStrategy(DiskCacheStrategy.ALL).into(imgNavHeaderBg);
Glide.with(this).load(urlProfileImg).thumbnail(0.5f).bitmapTransform(new CircleTransform(this)).diskCacheStrategy(DiskCacheStrategy.ALL).into(imgProfile);
navigationView.getMenu().getItem(4).setActionView(R.layout.menu_dot);
}
private void loadHomeFragment() {
selectNavMenu();
setToolBarTitle();
if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
drawer.closeDrawers();
toggleFab();
return;
}
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
Fragment 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.commitAllowingStateLoss();
}
};
if (mPendingRunnable != null) {
mHandler.post(mPendingRunnable);
}
toggleFab();
drawer.closeDrawers();
invalidateOptionsMenu();
}
private Fragment getHomeFragment() {
switch (navItemIndex) {
case 0:
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
case 1:
ProfileFragment profileFragment = new ProfileFragment();
return profileFragment;
case 2:
RateusFragment rateusFragment = new RateusFragment();
return rateusFragment;
case 3:
ScoreFragment scoreFragment = new ScoreFragment();
return scoreFragment;
case 4:
NotificationsFragment notificationsFragment = new NotificationsFragment();
return notificationsFragment;
case 5:
SettingsFragment settingsFragment = new SettingsFragment();
return settingsFragment;
default:
return new HomeFragment();
}
}
private void setToolBarTitle() {
getSupportActionBar().setTitle(activityTitles[navItemIndex]);
}
private void selectNavMenu() {
navigationView.getMenu().getItem(navItemIndex).setCheckable(true);
}
private void setUpNavigationView() {
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_home:
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
break;
case R.id.nav_profile:
navItemIndex = 1;
CURRENT_TAG = TAG_PROFILE;
break;
case R.id.nav_rateus:
navItemIndex = 2;
CURRENT_TAG = TAG_RATEUS;
break;
case R.id.nav_score:
navItemIndex = 3;
CURRENT_TAG = TAG_SCORE;
break;
case R.id.nav_notifications:
navItemIndex = 4;
CURRENT_TAG = TAG_NOTIFICATIONS;
break;
case R.id.nav_settings:
navItemIndex = 5;
CURRENT_TAG = TAG_SETTINGS;
break;
case R.id.nav_about_us:
startActivity(new Intent(MainActivity.this, AboutUsActivity.class));
drawer.closeDrawers();
return true;
case R.id.nav_terms:
startActivity(new Intent(MainActivity.this, TermsActivity.class));
drawer.closeDrawers();
return true;
default:
navItemIndex = 0;
}
if (menuItem.isChecked()) {
menuItem.setChecked(false);
} else {
menuItem.setChecked(true);
}
menuItem.setChecked(true);
return true;
}
});
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
//when nav closed this will triggered - leaving blank so nothing won't happen
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
//when nav opened this will triggered - leaving blank so nothing won't happen
super.onDrawerOpened(drawerView);
}
};
drawer.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawers();
return;
}
if (shouldLoadHomeFragOnBackPress) {
if (navItemIndex != 0) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
return;
}
}
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (navItemIndex == 0) {
getMenuInflater().inflate(R.menu.main, menu);
}
if (navItemIndex == 4) {
getMenuInflater().inflate(R.menu.notifications, menu);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_logout) {
Toast.makeText(getApplicationContext(), "Logout user!", Toast.LENGTH_LONG).show();
return true;
}
if (id == R.id.action_mark_all_read) {
Toast.makeText(getApplicationContext(), "All marked as read!", Toast.LENGTH_LONG).show();
}
if (id == R.id.action_clear_notifications) {
Toast.makeText(getApplicationContext(), "All Cleared!", Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
private void toggleFab() {
if (navItemIndex == 0)
fab.show();
else
fab.hide();
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start"
tools:context=".activity.MainActivity">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
There are couple of problems with the code:
Make sure u add break in switch:
case R.id.nav_about_us:
startActivity(new Intent(MainActivity.this, AboutUsActivity.class));
drawer.closeDrawers();
break; //add break
case R.id.nav_terms:
startActivity(new Intent(MainActivity.this, TermsActivity.class));
drawer.closeDrawers();
break;
default:
navItemIndex = 0;
break;
Also your fragment not loading as you are not calling the function properly:
in your Switch case:
case R.id.nav_home:
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
Fragment fragment = getHomeFragment(); //get fragment based on index
ReplaceFragment(fragment); //now replace them and load new one
drawer.closeDrawers();
break;
in ReplaceFragment method write:
public void ReplaceFragment(Fragment r_fragment) {
if (r_fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame, r_fragment).commit();
} else {
// error in creating fragment
}
}
Also overWrite following methods:
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
drawerView.bringToFront(); //add this two lines
drawerView.requestLayout();
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
actionBarDrawerToggle.syncState();
}
i've a problem in android. When i try to select first item at startup, and select other item except the first item so i've two items selected. This is my code. I've added navigationView.getMenu().performIdentifierAction(R.id.menu_program, 0) to select the first item but i think that the problem comes from this (i don't know). Thanks
public class MainActivity extends AppCompatActivity {
private DrawerLayout drawerLayout;
private Toolbar toolbar;
private NavigationView navigationView;
private ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = setupActionBarDrawerToggle();
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
navigationView = (NavigationView) findViewById(R.id.navigation_view);
setupNavigationViewContent(navigationView);
if (savedInstanceState == null) {
navigationView.getMenu().performIdentifierAction(R.id.menu_program, 0);
}
}
private ActionBarDrawerToggle setupActionBarDrawerToggle() {
return new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
}
private void setupNavigationViewContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
selectNavigationViewItem(item);
return true;
}
});
}
private void selectNavigationViewItem(MenuItem item) {
/*if (lastItem == null) {
lastItem = item;
item.setChecked(true);
Log.e("TAG", "selectNavigationViewItem: "+lastItem);
} else {
lastItem.setChecked(false);
}*/
Fragment fragment = null;
Class fragmentClass;
switch (item.getItemId()) {
case R.id.menu_program:
fragmentClass = Fragment1.class;
break;
case R.id.menu_visitor:
fragmentClass = Fragment2.class;
break;
case R.id.menu_partner:
fragmentClass = Fragment3.class;
break;
case R.id.menu_about:
fragmentClass = Fragment4.class;
break;
case R.id.menu_team:
fragmentClass = Fragment5.class;
break;
case R.id.menu_contact:
fragmentClass = Fragment6.class;
break;
default:
fragmentClass = Fragment1.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_layout_content, fragment).commit();
item.setChecked(true);
setTitle(item.getTitle());
drawerLayout.closeDrawers();
}
#Override
public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onPostCreate(savedInstanceState, persistentState);
actionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
}
When you are doing item.setChecked(true), you have to uncheck previous one.
Declare a MenuItem menuItem outside functions and replace your item.setChecked(true) with following code:
if(menuItem != null)
menuItem.setChecked(false);
menuItem = item;
menuItem.setChecked(true);
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.