android Navigation-drawer ,switching between fragment - android

When i switch between fragments in Navigation-drawer, Navigation-drawer closes slowly , i assume it waits to replace the newly selected fragment and closes the drawer,
How can i speed up it? In Gmail app, when you select a tab in Navigation-drawer,the new fragment is not created immediately,instead it shows a ProgressBar,then content is load,Also Navigation-drawer closing is speed here.
How can i do it, Any code example is appreciated.
Edit
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
.....
navigationDrawerTitles = getResources().getStringArray(R.array.navigation_drawer_titles);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, navigationDrawerTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
.......
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
switch(position){
case 0:
getFragmentManager().beginTransaction()
.replace(R.id.content_frame, new HomeFragment(), "HomeFragment").commit();
mDrawerList.setItemChecked(position, true);
setTitle(navigationDrawerTitles[position]);
break;
case 1:
getFragmentManager().beginTransaction()
.replace(R.id.content_frame, new HistoryFragment(), "HistoryFragment").commit();
mDrawerList.setItemChecked(position, true);
setTitle(navigationDrawerTitles[position]);
break;
case 2:
Intent sintent = new Intent(MainActivity.this,
SettingsActivity.class);
startActivity(sintent);
break;
default:
break;
}
mDrawerLayout.closeDrawer(mDrawerList);
}
Thanks,

I think this link will help you: Speed up Android Navigation drawer
public boolean smoothSlideViewTo(... int duration) {
...
return forceSettleCapturedViewAt(... int duration);
}

You have to close drawer when you replace fragment like this:
if (drawerLayout.isDrawerOpen(Gravity.START)) {
drawerLayout.closeDrawers();
}else{
drawerLayout.openDrawer(Gravity.START);
}
// your code to replace or add fragment
NOTE:- Change Gravity.START to Gravity.END if your drawer is open from right side. first close drawer and then replace fragment

Related

how to get progress circle before loading fragment on click of item in the navigation drawer

I have a navigation drawer in my app.On the click of an item from the navigation drawer particular fragment gets loaded.
but loading of a fragment is taking time of few seconds. i want a progress spinner to display in between so that it does not look like it got stuck.
i tried for using asynchronous task but it did not work because loading fragment from drawer does not include any background process.
Please suggest me something.
Navigation Drawer Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_navigation_fragments);
toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.test_nav_tool);
setSupportActionBar(toolbar);
SharedPreferences w = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor share = w.edit();
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
nvDrawer = (NavigationView) findViewById(R.id.nvView);
////if user skip-logout button in nav drawer will disable.
loggedIn=(w.getBoolean("loggedIn", loggedIn));
if(loggedIn==false){
nvDrawer.getMenu().findItem(R.id.logout).setVisible(false);
}
String user_name = (w.getString("name", user));
String type = "b";
type=(w.getString("type", type));
if(user_name.equalsIgnoreCase("name"))
user_name="Guest User";
if(type.equalsIgnoreCase("b")){
nvDrawer.getMenu().findItem(R.id.add_kitchen).setVisible(false);
nvDrawer.getMenu().findItem(R.id.nav_slideshow).setVisible(false);
}
header = LayoutInflater.from(this).inflate(R.layout.test_header_xml, null);
nvDrawer.addHeaderView(header);
TextView tv1=(TextView)header.findViewById(R.id.upload_image);
tv1.setText(user_name);
setupDrawerContent(nvDrawer);
drawerToggle=setupDrawerToggle();
mDrawer.addDrawerListener(drawerToggle);
if (savedInstanceState == null) {
nvDrawer.getMenu().performIdentifierAction(R.id.nav_camera, 0);
}
}
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(TestNavigationFragments.this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
Fragment fragment = null;
setTitle(menuItem.getTitle());
switch(menuItem.getItemId()) {
case R.id.nav_camera:
fragment=new TESTfragNEIBMAP();
break;
case R.id.nav_share:
fragment = new TestFragACCOUNT();
break;
case R.id.nav_send:
fragment = new TESTfragSUPPORT();
break;
case R.id.add_kitchen:
fragment = new TestfragSELLER();
break;
case R.id.nav_slideshow:
fragment=new TestAddKitchenHistory();
break;
case R.id.nav_gallery:
fragment=new TestNavOrder();
break;
case R.id.logout:
try {
SharedPreferences s = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = s.edit();
editor.clear().commit();
Intent intent = new Intent(this, Login.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
break;
}catch (Exception e){
Intent intent = new Intent(this, Login.class);
startActivity(intent);
}
case R.id.nav_track:
fragment = new TestTrack();
break;
}
if(fragment!=null){
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
mDrawer.closeDrawers();
}
}
UPDATE
I have also tried writing progess code in drawer activity and dismiss it in Fragment onViewCreated() method...but i did not see any progress spinner at the time when i click on item of drawer because map is opened and it called its onViewCreated method very fast.
the other option can be adding splash screen on click of item in drawer till map will load but i don't have idea how to do it like how to finish splash screen when the map will become properly visible.
ProgressDialog progress; // Global varibale
// Initiate it in `OnCreateView()`
progress = ProgressDialog.show(getActivity(), "dialog title",
"dialog message", true);
//When Loaded data
progress.dismiss();
i got the issue resolved by closing the drawer before loading the fragments using handler class and set the progress dialog code in onClick of navigation drawer item.

Android title changes but fragment stays the same after replace commit

I have a simple navigation drawer. When I click on the item to change the current fragment it runs the code for the replace command runs but the fragment does not change.
Here is how I setup the navigation drawer:
private void setupNavigationMenu(final Bundle savedInstanceState) {
final DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.nav_drawer_items);
// Create the navigation drawer.
navigationDrawer = new NavigationDrawer(this, toolbar, drawerLayout, mDrawerList,
R.id.main_fragment_container);
String[] osArray = {"Discover Tunes", "My Discovered Tunes"};
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
mDrawerList.setAdapter(mAdapter);
if (savedInstanceState == null) {
// Add the home fragment to be displayed initially.
discoverSongs();
}
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0){
discoverSongs();
drawerLayout.closeDrawers();
} else {
myDiscoveredSongs();
drawerLayout.closeDrawers();
}
}
});
As you can see above I have onitemclicklistner running the functions discoverSongs() and myDiscoveredSongs(). When I click on the list I can see that the correct position is working and the correct function is running. But the fragment for discoverSongs() is always showing up.
Here is my discoverSongs() function:
public void discoverSongs() {
final Fragment fragment = new DiscoverSongFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_fragment_container, fragment, DiscoverSongFragment.class.getSimpleName())
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
setTitle("Discover Tunes");
And my myDiscoveredSongs() function looks like this:
public void myDiscoveredSongs() {
final Fragment fragment = new DiscoverSongFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_fragment_container, fragment, MyDiscoveredSongsFragment.class.getSimpleName())
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
setTitle("My Discovered Tunes");
}
Thanks for your help.
You are use same fragment name inmyDiscoveredSongs() method so change this line you code
final Fragment fragment = new DiscoverSongFragment();
in inmyDiscoveredSongs().

How to navigate to previous fragment using back-button within NavigationDrawer?

I know that similar questions have been asked before, but I can't seem to find exactly what I’m looking for. My problem is that my back button is currently exiting the app. What I’m trying to do is to make it navigate to the previous fragment. Like if you open fragment1 - > fragment2 and then press the back button it would take you back to fragment1.
My current code looks like this.
public class MainActivity extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPageTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mPageTitles = getResources().getStringArray(R.array.menu_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPageTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
)
{
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Sets the firstpage if no state is found
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content
// view
return super.onPrepareOptionsMenu(menu);
}
// Toogles the drawer menu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return mDrawerToggle.onOptionsItemSelected(item);
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
switch (position) {
case 0:
KontaktInfoFragment kontakt = new KontaktInfoFragment();
fragmentTransaction.replace(R.id.content_frame, kontakt);
fragmentTransaction.addToBackStack("Replace");
fragmentTransaction.commit();
break;
case 1:
OmOssFragment omoss = new OmOssFragment();
fragmentTransaction.replace(R.id.content_frame, omoss);
fragmentTransaction.addToBackStack("Replace");
fragmentTransaction.commit();
break;
case 2:
MainScreenActivity mainscreen = new MainScreenActivity();
fragmentTransaction.replace(R.id.content_frame, mainscreen);
fragmentTransaction.addToBackStack("Replace");
fragmentTransaction.commit();
break;
case 3:
LoginFragment login = new LoginFragment();
fragmentTransaction.replace(R.id.content_frame, login);
fragmentTransaction.addToBackStack("Replace");
fragmentTransaction.commit();
break;
case 4:
ContactFormFragment form = new ContactFormFragment();
fragmentTransaction.replace(R.id.content_frame, form);
fragmentTransaction.addToBackStack("Replace");
fragmentTransaction.commit();
break;
}
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPageTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
}
When you press back button inside your fragment onBackPressed() method of your activity will be called if you have declared that..So handling back button for fragments within navigation drawer can be one in this way..
MainActvity
public static boolean isMainActivityShown ;
public static boolean isFragment1Shown=false ;
public static boolean isFragment2Shown=false ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isMainActivityShown=true //inside onCreate method put isMainActivityShown true
.
.
.
}
Fragment currentFragment = new Fragment1();
isMainActivityShown=false; //when moving to fragment1
isFragment1Shown=true;
frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, currentFragment)
.commit();
#Override
public void onBackPressed() {
if(isMainActivityShown)
{
finish();
}
else if(isFragment1Shown)
{
//write the code to handle back button when you are in Fragment1
}
else if(isFragment2Shown)
{ //When you are in Fragment 2 pressing back button will move to fragment1
Fragment currentFragment = new Fragment1();
isFragment2Shown=false;
isFragment1Shown=true;
FragmentManager frgManager;
frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, currentFragment)
.commit();
}
}
Fragment1
Fragment currentFragment = new Fragment2();
MainActivity.isFragment1Shown=false;
MainActivity.isFragment2Shown=true;
frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, currentFragment)
.commit();

Error in SherlockFragment when switching items in slide Menu

I'm having lot of problems when implementing ActionBar Sherlock, the last one is this one. I have an Slide Menu whith 3 options in my ActionBar. My problem is that when I choose one item (it load a fragment) that has been previously selected the app crash. The log error is
The specified child already has a parent. You must call removeView()
on the child's parent first.
It mark a line where I add view to a HorizontalScroller.
lls.addView(mviews.get(i));
In my OnCreateView I have
final View v = inflater.inflate(R.layout.activity_landing, container,false);
container.removeAllViews();
I haved tried many different ways posted here, but I don't get thw solution to my problem. Any ideas?
EDIT:
Here is some code of my MainActivity and Fragment.
This is the MainActivity. Ther's a ScreenSplash after and a class that extends from Application that control all WebService communications.
public class MainActivity extends SherlockFragmentActivity {
//Declare Variables
//...
Fragment fragment1 = new Fragment1();
Fragment fragment2 = new Fragment2();
Fragment fragment3 = new Fragment3();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().setIcon(R.drawable.ic_launcher);
getSupportActionBar().setTitle("");
setContentView(R.layout.drawer_main);
// Generate title
title = new String[] { "Item 1", "Item 2", "Item 3", "Item 4" };
// Generate icon
icon = new int[] { R.drawable.item1, R.drawable.item2,
R.drawable.item3, R.drawable.item4};
// Locate DrawerLayout in drawer_main.xml
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// Locate ListView in drawer_main.xml
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// Pass results to MenuListAdapter Class
mMenuAdapter = new MenuListAdapter(this, title, subtitle, icon);
// Set the MenuListAdapter to the ListView
mDrawerList.setAdapter(mMenuAdapter);
// Capture button clicks on side menu
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// Enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
// TODO Auto-generated method stub
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
//FOR ABS y ND
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.activity_main, menu);
//Define ActionBar buttons and actions
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//Sliding lateral Menu
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
return super.onOptionsItemSelected(item);
}
// The click listener for ListView in the navigation drawer
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Locate Position
switch (position) {
case 0:
ft.replace(R.id.content_frame, fragment1);
break;
case 1:
ft.replace(R.id.content_frame, fragment2);
break;
case 2:
ft.replace(R.id.content_frame, fragment3);
break;
}
ft.commit();
mDrawerList.setItemChecked(position, true);
// Close drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
This is the fragment with error. Now the other two are empty.
public class Fragment1 extends SherlockFragment implements
AdapterView.OnItemClickListener {
//DeclareVariables
public Fragment1() {
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//some declaration ad settings (witdhs, typefaces, caches,...)
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.main_activity, null,
false);
container.removeAllViews();
lls = (LinearLayout) v.findViewById(R.id.lscroll_item);
lls.removeAllViews();
//Instantiate some elements of the view such as TextViews and ImageViews
//layoutParams
// Show Scroll
DataStore.sharedInstance().getInfo(
new DataStore.infoReturn() {
#Override
public void call(final ArrayList<User> users, int error) {
if(users != null){
for (i = 0; i < users.size(); i++) {
mviews.add((RelativeLayout) getActivity().getLayoutInflater().inflate(R.layout.item_user, null));
mviews.get(i).setLayoutParams(layoutParams2);
imv = (ImageView) mviews.get(i).findViewById(R.id.user);
imv.getLayoutParams().height=friend_height;
imv_click = (ImageView) mviews.get(i).findViewById(R.id.click);
TextView text2 = (TextView) mviews.get(i).findViewById(R.id.fav);
text2.setTypeface(myTypeFace);
//set widths and layoutParams and sources
mviews.get(i).setId(i);
//NEXT LINE IS THE CRASH POINT, WHERE I TRY TO ADD ITEMS TO THE VIEW
lls.addView(mviews.get(i));
mviews.get(i).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
//Set actins when click
}
});
}
}else{
switch (error) {
case -1: //ERROR OBTENER USERS
break;
default:
break;
}
}
}
});
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// actions when click
}
#Override
public void onResume() {
super.onResume();
refreshInfo();
refreshSelectedUsers();
}
#Override
public void onPause() {
super.onPause();
DataStore.sharedInstance().setSelectedUsers(mSelected);
}
#Override
public void onDestroy() {
super.onDestroy();
//delete cache
}
//Some other methods for other UI items.
}
I have hidden some code to make it easier to read.
Use this
final View v = inflater.inflate(R.layout.activity_landing, null, false);
instead of
final View v = inflater.inflate(R.layout.activity_landing, container,false);

Switching entire fragments in NavigationDrawer

I was working my way through the NavigationDrawer sample code from developer.android.com and tried to implement it as navigation for one of my apps. However, I came across a problem when it came to switching fragments in the main window, as the sample code reuses the same fragment and just switches out an imageview. Here is the code from the sample:
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
where PlanetFragment is a generic fragment with only an imageview and no functionality, which does not apply for my app. So, instead, I tried and replaced the first block of the selectItem method with a case/switch:
public void selectItem(int position){
Fragment fragment;
switch(position){
case 1: fragment = new Fragmentscreentest(); break;
case 2: fragment = new Fragmentstatusbar(); break;
case 3: fragment = new Fragmentfullscreen(); break;
default: fragment = new Fragmentscreentest(); break;
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
and added the same empty constuctor to my Fragments as the PlanetFragment has:
public Fragmentstatus() {
// Empty constructor required for fragment subclasses
}
It doesn't work, whenever I open up the app, it only shows the app icon and the title in the actionbar, no content, no actions on the actionbar, no navigation drawer, nothing and then it crashes after about a second. With the original code it works and shows everything, but that only works for one fragment.
How can I actually switch Fragments in the NavigationDrawer?
Take a look at my code:
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
switch (position) {
case 0:
fragmentManager.beginTransaction()
.replace(R.id.content_frame, new MainActivityFragment())
.commit();
break;
case 1:
fragmentManager.beginTransaction()
.replace(R.id.content_frame, new DbListViewFragment())
.commit();
break;
case 2:
fragmentManager.beginTransaction()
.replace(R.id.content_frame, new StatisticsFragment())
.commit();
break;
case 3:
fragmentManager.beginTransaction()
.replace(R.id.content_frame, new CalculatorFragment(), "calculator")
.commit();
break;
}
I am using a switch-case. position 0 is the very first item in my ListView inside the drawer.
Taken from my answer on this question: DrawerLayout on click disabled after first event
EDIT:
If you want to select one Fragment at start you can do it like this at the end of your onCreate method:
if (savedInstanceState == null) {
selectItem(0);
}
0 being the position of your desired Fragment

Categories

Resources