i'm using a navigation drawer to switch between fragments , each time i move to a new one ,it's completely recreated and the previous one is completely destroyed, so i want to conserve the state of fragments while swapping and back again
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
Fragment fragment=getHomeFragment();
fragmentTransaction.replace(R.id.frame,fragment,CURRENT_TAG);
fragmentTransaction.commitAllowingStateLoss();
}
};
if (mPendingRunnable != null) {
mHandler.post(mPendingRunnable);
}
and the getHomeFragment() :
public Fragment getHomeFragment() {
switch (navItemIndex) {
case 0:
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
case 1:
BoiteRFragment boiteRFragment = new BoiteRFragment();
return boiteRFragment;
case 2:
InfoPersFragment infoPersFragment = new InfoPersFragment();
return infoPersFragment;
case 3:
NotificationsFragment notificationsFragment = new NotificationsFragment();
return notificationsFragment;
case 4:
PrametresFragment prametresFragment = new PrametresFragment();
return prametresFragment;
default:
return new HomeFragment();
}
}
This code shows an error :
private void selectItem(int position) {
Fragment fragment;
switch (position)
{
case 1:
fragment = new PizzaFragment();
break;
case 2:
fragment = new PastaFragment();
break;
case 3:
fragment = new StoresFragment();
break;
default:
fragment = new TopFragment();
}
android.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame,fragment);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
when I initialize fragment with new PizzaFragment or PastaFragment, android studio shows an error "Incompatible types"
you have to create object of that fragment .It will work.
switch (position)
{
case 1:
PizzaFragment fragment = new PizzaFragment();
// apply FragmentTransaction
break;
case 2:
PastaFragment fragment = new PastaFragment();
// apply FragmentTransaction
break;
case 3:
StoresFragment fragment = new StoresFragment();
// apply FragmentTransaction
break;
default:
TopFragment fragment = new TopFragment();
// apply FragmentTransaction
}
I did the same once and the mistake was that the PizzaFragment and PastatFragent classes were not extending the Fragment, just look at that for once
Like
PizzaFragment extends Fragment{
and
PastaFragment extends Fragment{
And Maybe
you are importing different packages,so check your import statements
I have a navigation drawer in my activity and add the fragments on drawer item clicked
For adding the fragment
Fragment fragment = null;
switch (position) {
case 0:
fragment = new Fragment()1;
break;
case 1:
fragment = new Fragment()2;
break;
case 2:
fragment = new Fragment()3;
break;
case 3:
fragment = new Fragment()4;
break;
case 4:
fragment = new Fragment()5;
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.frame_container, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
closeDrawer();
} else {
Logger.e("MainActivity", "Error in creating fragment");
}
Whenever I switch back from one fragment to another fragment the view is inflated again as in previous fragment was destroyed and it is being created again.
How can I stop it from being recreated?
Fragment fragment1 = null;
Fragment fragment2 = null;
Fragment fragment3 = null;
Fragment fragment4 = null;
Fragment fragment5 = null;
switch (position) {
case 0:
if (fragment1 == null) {
fragment1 = new Fragment()1;
}
break;
case 1:
if (fragment2 == null) {
fragment2 = new Fragment()2;
}
break;
case 2:
if (fragment3 == null) {
fragment3 = new Fragment()3;
}
break;
case 3:
if (fragment4 == null) {
fragment4 = new Fragment()4;
}
break;
case 4:
if (fragment5 == null) {
fragment5 = new Fragment()5;
}
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.frame_container, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
closeDrawer();
} else {
Logger.e("MainActivity", "Error in creating fragment");
}
The navigation drawer lags every time I open a new activity. I looked on Google for a solution and I found out that I can solve it by delaying the new activity with a Handler. I experimented a little bit but got nowhere.
Some code pieces from MainActivity.java:
public void SelectItem(int possition) {
Fragment fragment = null;
Bundle args = new Bundle();
switch (possition) {
case 2:
fragment = new FragmentZero();
break;
case 3:
fragment = new FragmentOne();
break;
case 4:
fragment = new FragmentTwo();
break;
case 5:
fragment = new FragmentThree();
break;
case 7:
fragment = new FragmentTwo();
break;
case 8:
fragment = new FragmentZero();
break;
case 9:
fragment = new FragmentOne();
break;
case 10:
fragment = new FragmentTwo();
break;
case 11:
fragment = new FragmentZero();
break;
case 12:
fragment = new FragmentOne();
break;
case 14:
fragment = new FragmentZero();
break;
case 15:
fragment = new FragmentOne();
break;
case 16:
fragment = new FragmentTwo();
break;
default:
break;
}
fragment.setArguments(args);
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment)
.commit();
mDrawerList.setItemChecked(possition, true);
setTitle(dataList.get(possition).getItemName());
mDrawerLayout.closeDrawer(mDrawerList);
}
and
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if (dataList.get(position).getTitle() == null) {
SelectItem(position);
}
}
}
In your activity create a handler and initialize it in your on create method
private Handler mHandler;
mHandler = new Handler();
then change your drawer item click listener to this.
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position,
long id) {
if (dataList.get(position).getTitle() == null) {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
SelectItem(position);;
}
}, 250);
}
mDrawerList.setItemChecked(possition, true);
mDrawerLayout.closeDrawer(mDrawerList);
}
}
and change SelectItem method to this
public void SelectItem(int possition) {
Fragment fragment = null;
Bundle args = new Bundle();
switch (possition) {
case 2:
fragment = new FragmentZero();
break;
case 3:
fragment = new FragmentOne();
break;
case 4:
fragment = new FragmentTwo();
break;
case 5:
fragment = new FragmentThree();
break;
case 7:
fragment = new FragmentTwo();
break;
case 8:
fragment = new FragmentZero();
break;
case 9:
fragment = new FragmentOne();
break;
case 10:
fragment = new FragmentTwo();
break;
case 11:
fragment = new FragmentZero();
break;
case 12:
fragment = new FragmentOne();
break;
case 14:
fragment = new FragmentZero();
break;
case 15:
fragment = new FragmentOne();
break;
case 16:
fragment = new FragmentTwo();
break;
default:
break;
}
fragment.setArguments(args);
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment)
.commit();
setTitle(dataList.get(possition).getItemName());
}
There's a time come when someone include some codes without explaining. Well, this time it's this case because the codes aren't hard at all.
I'm trying to switch fragments in sliding drawer.
Codes:
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
Here's DrawerItemClickListener Class:
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) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
Fragment frag = null;
switch (position) {
case 0:
ft.replace(R.id.content_frame, Algeria);
break;
case 1:
ft.replace(R.id.content_frame, Bahrain);
break;
case 2:
ft.replace(R.id.content_frame, Comoros);
break;
case 3:
ft.replace(R.id.content_frame, Djibouti);
break;
case 4:
ft.replace(R.id.content_frame, Egypt);
break;
case 5:
ft.replace(R.id.content_frame, Iraq);
break;
case 6:
ft.replace(R.id.content_frame, Jordan);
break;
case 7:
ft.replace(R.id.content_frame, Kuwait);
break;
case 8:
ft.replace(R.id.content_frame, Lebanon);
break;
case 9:
ft.replace(R.id.content_frame, Libya);
break;
case 10:
ft.replace(R.id.content_frame, Mauritania);
break;
case 11:
ft.replace(R.id.content_frame, Morocco);
break;
case 12:
ft.replace(R.id.content_frame, Oman);
break;
case 13:
ft.replace(R.id.content_frame, Pelastine);
break;
case 14:
ft.replace(R.id.content_frame, Qatar);
break;
case 15:
ft.replace(R.id.content_frame, Saudi_Arabia);
break;
case 16:
ft.replace(R.id.content_frame, Somalia);
break;
case 17:
ft.replace(R.id.content_frame, Sudan);
break;
case 18:
ft.replace(R.id.content_frame, Syria);
break;
case 19:
ft.replace(R.id.content_frame, Tunisia);
break;
case 20:
ft.replace(R.id.content_frame, Emirates);
break;
case 21:
ft.replace(R.id.content_frame, Yemen);
break;
}
ft.commit();
}
BUT IT DOESN'T WORK
No bugs at all, just nothing show at the screen! i know the fragment work 100% but it doesn't show on the screen. Well WHY!?
Thanks. :)
UPDATE FUL CODES:
public class Drawer extends SherlockFragmentActivity {
MenuListAdapter mMenuAdapter;
String[] title;
String[] subtitle;
int[] icon;
SharedPreferences prefs;
public static String prefName = "SecretFile";
Fragment Algeria = new Fragment1();
Fragment Bahrain = new Fragment2();
Fragment Comoros = new Fragment3();
Fragment Djibouti = new Fragment4();
Fragment Egypt = new Fragment5();
Fragment Iraq = new Fragment6();
Fragment Jordan = new Jordan();
Fragment Kuwait = new Fragment8();
Fragment Lebanon = new Lebanon();
Fragment Libya = new Fragment10();
Fragment Mauritania = new Fragment11();
Fragment Morocco = new Fragment12();
Fragment Oman = new Fragment13();
Fragment Pelastine = new Fragment14();
Fragment Qatar = new Qatar();
Fragment Saudi_Arabia = new Fragment16();
Fragment Somalia = new Fragment17();
Fragment Sudan = new Fragment18();
Fragment Syria = new Fragment19();
Fragment Tunisia = new Fragment20();
Fragment Emirates = new Fragment21();
Fragment Yemen = new Fragment22();
ConnectivityManager connMgr;
NetworkInfo networkInfo;
ListView mDrawerList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SlidingMenu sm = new SlidingMenu(this);
title = getResources().getStringArray(R.array.country_array);
icon = new int[] { R.drawable.algeria, R.drawable.bahrain,
R.drawable.comoros, R.drawable.djibouti, R.drawable.egypt,
R.drawable.iraq, R.drawable.jordan, R.drawable.kuwait,
R.drawable.lebanon, R.drawable.libya, R.drawable.mauritania,
R.drawable.morocco, R.drawable.oman, R.drawable.pelastine,
R.drawable.qatar, R.drawable.saudiarabia, R.drawable.somalia,
R.drawable.sudan, R.drawable.syria, R.drawable.tunisia,
R.drawable.emirates, R.drawable.yemen, };
sm.setMenu(R.layout.drawer_main);
sm.setShadowWidthRes(R.dimen.shadow_width);
sm.setShadowDrawable(R.drawable.shadow);
sm.setMode(SlidingMenu.LEFT_RIGHT);
sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
sm.setFadeDegree(0.7f);
sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
getActionBar().setDisplayHomeAsUpEnabled(true);
sm.setSecondaryMenu(R.layout.menu_frame);
sm.setSecondaryShadowDrawable(R.drawable.shadow);
sm.attachToActivity(this, SlidingMenu.SLIDING_WINDOW);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mMenuAdapter = new MenuListAdapter(this, title, icon);
mDrawerList.setAdapter(mMenuAdapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
private int seethefirstactivity() {
// TODO Auto-generated method stub
int fragmento;
connMgr = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
networkInfo = connMgr.getActiveNetworkInfo();
fragmento = prefs.getInt("country", 1);
if (fragmento == 0) {
Algeria = new Fragment1();
} else if (fragmento == 1) {
Bahrain = new Fragment2();
} else if (fragmento == 2) {
Comoros = new Fragment3();
} else if (fragmento == 3) {
Djibouti = new Fragment4();
} else if (fragmento == 4) {
Egypt = new Fragment5();
} else if (fragmento == 5) {
Iraq = new Fragment6();
} else if (fragmento == 6) {
Jordan = new Jordan();
} else if (fragmento == 7) {
Kuwait = new Fragment8();
} else if (fragmento == 8) {
Lebanon = new Lebanon();
} else if (fragmento == 9) {
Libya = new Fragment10();
} else if (fragmento == 10) {
Mauritania = new Fragment11();
} else if (fragmento == 11) {
Morocco = new Fragment12();
} else if (fragmento == 12) {
Oman = new Fragment13();
} else if (fragmento == 13) {
Pelastine = new Fragment14();
} else if (fragmento == 14) {
Qatar = new Qatar();
} else if (fragmento == 15) {
Saudi_Arabia = new Fragment16();
} else if (fragmento == 16) {
Somalia = new Fragment17();
} else if (fragmento == 17) {
Sudan = new Fragment18();
} else if (fragmento == 18) {
Syria = new Fragment19();
} else if (fragmento == 19) {
Tunisia = new Fragment20();
} else if (fragmento == 20) {
Emirates = new Fragment21();
} else if (fragmento == 21) {
Yemen = new Fragment22();
}
return fragmento;
}
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) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
Fragment frag = null;
switch (position) {
case 0:
ft.replace(R.id.content_frame, Algeria);
break;
case 1:
ft.replace(R.id.content_frame, Bahrain);
break;
case 2:
ft.replace(R.id.content_frame, Comoros);
break;
case 3:
ft.replace(R.id.content_frame, Djibouti);
break;
case 4:
ft.replace(R.id.content_frame, Egypt);
break;
case 5:
ft.replace(R.id.content_frame, Iraq);
break;
case 6:
ft.replace(R.id.content_frame, Jordan);
break;
case 7:
ft.replace(R.id.content_frame, Kuwait);
break;
case 8:
ft.replace(R.id.content_frame, Lebanon);
break;
case 9:
ft.replace(R.id.content_frame, Libya);
break;
case 10:
ft.replace(R.id.content_frame, Mauritania);
break;
case 11:
ft.replace(R.id.content_frame, Morocco);
break;
case 12:
ft.replace(R.id.content_frame, Oman);
break;
case 13:
ft.replace(R.id.content_frame, Pelastine);
break;
case 14:
ft.replace(R.id.content_frame, Qatar);
break;
case 15:
ft.replace(R.id.content_frame, Saudi_Arabia);
break;
case 16:
ft.replace(R.id.content_frame, Somalia);
break;
case 17:
ft.replace(R.id.content_frame, Sudan);
break;
case 18:
ft.replace(R.id.content_frame, Syria);
break;
case 19:
ft.replace(R.id.content_frame, Tunisia);
break;
case 20:
ft.replace(R.id.content_frame, Emirates);
break;
case 21:
ft.replace(R.id.content_frame, Yemen);
break;
}
ft.commit();
}
}
Ok so i think you haven't used MyApplication class much.. no problem i will show you:
MyApplication class we could say it's a "common", accessible class used to store/restore data with methods at any time in you App:
So let's start:
in your Manifest:
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="myPackageName"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
if you see in the code there is " android:name=".MyApplication" " thats your MyApplication class name you will create in your project.
Now we just create a simple class and extends to " Application "
package youPackageName;
public class MyApplication extends Application {
/**
* IN HERE WILL BE ALL YOUR VARIABLES AND METHODS
*/
}
so how to use it?
easy...
we will say that you whant to save a simple string ok? with methods to get and set that string
package youPackageName;
public class MyApplication extends Application {
String mString = "";
// To set my string
public void setMyString(String s){
this.mString = s;
}
// get string
public String getMyString(){
return this.mString;
}
// one you seted ones that string it will be abailable at any moment while your app is not destroyed
}
From your activity we will call that method in that app class how?
MyApplication MyApp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyApp = ((MyApplication)getApplicationContext());
//SET
MyApp.setMyString("HELLO");
//GET
String a = MyApp.getMyString();
}
NOW ! FRAGMENTS!
My layout is very simple:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="#+id/main_frag"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
in your MainActivity:
// myNewFragment: FRAG TO BE REPLACE
public void changeFragment(Fragment myNewFragment) {
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
t.replace(R.id.main_frag, myNewFragment);
t.commit();
}
in your MyApplication class we just created before
public void switchFragmentNormal(Activity a, Fragment newContent) {
MainActivity fca = (MainActivity)a;
fca.changeFragment(newContent);
}
And NOW Finally from any fragment or SlideMenu
Just do this;
MyApplication MyApp;
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
MyApp = (MyApplication)getActivity().getApplicationContext();
MyApp.switchFragmentNormal(getActivity(), new FragmentVote());
}
And thats it, now you have a class that's available at any time where you can store variables methods etc.
:-)
When I work with fragments I doit this way:
In the MainActivity:
public void changeFragment(int frag, Fragment myNewFragment) {
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
t.replace(frag, myNewFragment);
//t.addToBackStack(null);
t.commit();
}
And the in my MyApplication class y have small functions so I can call them any time:
public void switchFragmentNormal(Activity a, Fragment newContent) {
MainActivity fca = (MainActivity)a;
fca.changeFragment(R.id.main_fragment, newContent);
}
So this way, from any fragment or slide menu i do a small call and I will change it easily:
and I make a "new somthing()" just when I need to:
FragmentVote fvote = new FragmentVote();
MyApp.switchFragmentNormal(getActivity(), fvote);
to change fragment and close the slidemenu "SlidingMenu- made by : jfeinstein10" do it this way:
SlidingMenu sm = getSlidingMenu();
sm.setMode(SlidingMenu.LEFT_RIGHT);
...
public void changeFragmentFromList(int frag, Fragment myNewFragment) {
sm.toggle(); // this closes the slidemenu
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
t.replace(frag, myNewFragment);
t.commit();
}
and to call it: MyApplication class
public void switchFragmentNormalList(Activity a, Fragment newContent) {
MainActivity fca = (MainActivity)a;
fca.changeFragmentFromList(R.id.main_fragment, newContent);
}
Then: and I make a "new somthing()" just when I need to:
FragmentVote fvote = new FragmentVote();
MyApp.switchFragmentNormalList(getActivity(), fvote);
Then sometimes i want to add to stack my fragment so i can do other stuff etc.
check this:
https://stackoverflow.com/a/17978786/2625912
Hope help you !