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();
}
}
I just want to call fragment from this class.
Actually i have many fragments in my app and have to call them again and again.
So i thought to make a class and a function for loading a fragment so whenever i need to call a fragment i can use the function of this class.
But iam unable to get getSupportFragmentManager() here.
I tried by extending the class to fragment but then it produces null exception.
also by extending with Appcompactactivity and uses getSupportFragmentManager(); but is also gives error by saying the activity destroyed.
So anyone have solution to call a fragment from a simple class?
public class CompletedandPendingScreensLoader {
public void pendingscreenLoader(int serialnumber){
Fragment frag = null;
switch (serialnumber){
case 1:
frag = new LessonOne();
break;
case 2:
frag = new LessonTwo();
break;
case 3:
frag = new LessonThree();
break;
case 4:
frag = new LessonFour();
break;
case 5:
frag = new LessonFive();
break;
}
if (frag != null) {
Bundle bundle = new Bundle();
bundle.putString("pending","pen");
frag.setArguments(bundle);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.frame, frag).addToBackStack(null); // replace a Fragment with Frame Layout
transaction.commit(); // commit the changes
}
}
public void completedscreenLoader(int serialnumber){
Fragment frag = null;
switch (serialnumber){
case 1:
frag = new LessonOne();
break;
case 2:
frag = new LessonTwo();
break;
case 3:
frag = new LessonThree();
break;
case 4:
frag = new LessonFour();
break;
case 5:
frag = new LessonFive();
break;
}
if (frag != null) {
Bundle bundle = new Bundle();
bundle.putString("completed","yes");
frag.setArguments(bundle);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.frame, frag).addToBackStack(null); // replace a Fragment with Frame Layout
transaction.commit(); // commit the changes
}
}
public void simpleScreenLoader( int serialnumber){
Fragment frag = null;
switch (serialnumber){
case 1:
frag = new LessonOne();
break;
case 2:
frag = new LessonTwo();
break;
case 3:
frag = new LessonThree();
break;
case 4:
frag = new LessonFour();
break;
case 5:
frag = new LessonFive();
break;
}
if (frag != null) {
FragmentTransaction transaction = getFragmentManager.beginTransaction();
transaction.replace(R.id.frame, new LessonTwo()).addToBackStack(null); // replace a Fragment with Frame Layout
transaction.commit();
}
}
I believe you will at some point call this class from some activity or fragment if so then use the modified constructor it will open the fragment. else you can't do it without having a reference for FragmentManager from activity or fragment.
public class CompletedandPendingScreensLoader {
private FragmentManager fragmentManager = null;
//when ever you start your class just start using this constructor
CompletedandPendingScreensLoader(FragmentManager fragmentManager){
this.fragmentManager = fragmentManager
}
public void pendingscreenLoader(int serialnumber){
Fragment frag = null;
switch (serialnumber){
case 1:
frag = new LessonOne();
break;
case 2:
frag = new LessonTwo();
break;
case 3:
frag = new LessonThree();
break;
case 4:
frag = new LessonFour();
break;
case 5:
frag = new LessonFive();
break;
}
if (frag != null) {
Bundle bundle = new Bundle();
bundle.putString("pending","pen");
frag.setArguments(bundle);
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.frame, frag).addToBackStack(null); // replace a Fragment with Frame Layout
transaction.commit(); // commit the changes
}
}
public void completedscreenLoader(int serialnumber){
Fragment frag = null;
switch (serialnumber){
case 1:
frag = new LessonOne();
break;
case 2:
frag = new LessonTwo();
break;
case 3:
frag = new LessonThree();
break;
case 4:
frag = new LessonFour();
break;
case 5:
frag = new LessonFive();
break;
}
if (frag != null) {
Bundle bundle = new Bundle();
bundle.putString("completed","yes");
frag.setArguments(bundle);
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.frame, frag).addToBackStack(null); // replace a Fragment with Frame Layout
transaction.commit(); // commit the changes
}
}
public void simpleScreenLoader( int serialnumber){
Fragment frag = null;
switch (serialnumber){
case 1:
frag = new LessonOne();
break;
case 2:
frag = new LessonTwo();
break;
case 3:
frag = new LessonThree();
break;
case 4:
frag = new LessonFour();
break;
case 5:
frag = new LessonFive();
break;
}
if (frag != null) {
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.frame, new LessonTwo()).addToBackStack(null); // replace a Fragment with Frame Layout
transaction.commit();
}
}
Your class must extend AppCompatActivity class to call this function, and when you extend the class then you have to also override onCreate() method of the activity and you have to also set Layout for the activity in onCreate() Method
public class CompletedandPendingScreensLoader {
private AppCompatActivity myActivty;
public CompletedandPendingScreensLoader(AppCompatAcitivity myActivty)
{
this.myActivity = myActivity
}
public void pendingscreenLoader(int serialnumber){
Fragment frag = null;
switch (serialnumber){
case 1:
frag = new LessonOne();
break;
case 2:
frag = new LessonTwo();
break;
case 3:
frag = new LessonThree();
break;
case 4:
frag = new LessonFour();
break;
case 5:
frag = new LessonFive();
break;
}
if (frag != null) {
Bundle bundle = new Bundle();
bundle.putString("pending","pen");
frag.setArguments(bundle);
FragmentTransaction transaction =
myActivity.getFragmentManager().beginTransaction();
transaction.replace(R.id.frame, frag).addToBackStack(null); // replace a Fragment with Frame Layout
transaction.commit(); // commit the changes
}
}
public void completedscreenLoader(int serialnumber){
Fragment frag = null;
switch (serialnumber){
case 1:
frag = new LessonOne();
break;
case 2:
frag = new LessonTwo();
break;
case 3:
frag = new LessonThree();
break;
case 4:
frag = new LessonFour();
break;
case 5:
frag = new LessonFive();
break;
}
if (frag != null) {
Bundle bundle = new Bundle();
bundle.putString("completed","yes");
frag.setArguments(bundle);
FragmentTransaction transaction =
myAcitvity.getFragmentManager().beginTransaction();
transaction.replace(R.id.frame, frag).addToBackStack(null); // replace a Fragment with Frame Layout
transaction.commit(); // commit the changes
}
}
public void simpleScreenLoader( int serialnumber){
Fragment frag = null;
switch (serialnumber){
case 1:
frag = new LessonOne();
break;
case 2:
frag = new LessonTwo();
break;
case 3:
frag = new LessonThree();
break;
case 4:
frag = new LessonFour();
break;
case 5:
frag = new LessonFive();
break;
}
if (frag != null) {
FragmentTransaction transaction =
myActivity.getFragmentManager.beginTransaction();
transaction.replace(R.id.frame, new LessonTwo()).addToBackStack(null); // replace a Fragment with Frame Layout
transaction.commit();
}
}
There is problem with my fragment, they are showed together, one on the second fragment. How to disapear, and only show one of them?
Definiton:
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fr = new avc);
FragmentTransaction ft = ((TestingActivity)context).getFragmentManager().beginTransaction();
ft.replace(R.id.test, fr);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
});
And definiton of container below:
<FrameLayout
android:id="#+id/test"
android:layout_width="match_parent"
android:layout_height="match_parent" />
You can use some thing like this. Make a function for showing a fragment and call each time this function with different parameter.
eg. If You want to show "HomeFragment" then call displayView(0) and if you want to show "FindPeopleFragment" then call displayView(1)
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new FindPeopleFragment();
break;
case 2:
fragment = new PhotosFragment();
break;
case 3:
fragment = new CommunityFragment();
break;
case 4:
fragment = new PagesFragment();
break;
case 5:
fragment = new WhatsHotFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
i have a navigation drawer project which I just modify from the "Create New Project > Navigation Drawer" using Android Studio. There are several 'menus' in the navigation drawer, on each opens up different fragments.. the problem is every time when I navigate using the drawer, the fragments are re-created. Means that when the user have done some changes on a fragment, later when the user re-visits the fragment again, the changes are lost. I've used setRetainInstance(true); but that only works for orientation change it seems.
here's a part of my code on which I use to display the selected fragments:
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
Fragment fragment = null;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
FragmentManager fm = getFragmentManager();
switch (position) {
case 0:
fragment = fm.findFragmentByTag("fragmentDashboard");
if (fragment == null){
fragment = new Dashboard();
transaction.replace(R.id.container, fragment, "fragmentDashboard");
transaction.addToBackStack(null);
transaction.commit();
}else{
transaction.remove(getFragmentManager().findFragmentByTag("fragmentDashboard"));
transaction.commit();
fm.popBackStack();
}
break;
case 1:
fragment = fm.findFragmentByTag("fragmentExpenses");
if (fragment == null) {
fragment = new Expenses();
transaction.replace(R.id.container, fragment, "fragmentExpenses");
transaction.addToBackStack(null);
transaction.commit();
}else{
transaction.remove(getFragmentManager().findFragmentByTag("fragmentExpenses"));
transaction.commit();
fm.popBackStack();
}
break;
default:
break;
}
}
edit: this question Save fragment state with navigation drawer is the close solution I get to my problem, but the answer is too brief.. and I'm pretty new in android development. so can anyone help?
Try this Code :: Instead of replacing-fragments .... EveryTime Hide and Show the fragments
Description::
Instead of destroying the fragments .... create the fragment for
the first time and every other time find the fragment and use it,
instead of replacing it
Instead of code ::
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
Fragment fragment = null;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
FragmentManager fm = getFragmentManager();
switch (position) {
case 0:
fragment = fm.findFragmentByTag("fragmentDashboard");
if (fragment == null){
fragment = new Dashboard();
transaction.replace(R.id.container, fragment, "fragmentDashboard");
transaction.addToBackStack(null);
transaction.commit();
}else{
transaction.remove(getFragmentManager().findFragmentByTag("fragmentDashboard"));
transaction.commit();
fm.popBackStack();
}
break;
case 1:
fragment = fm.findFragmentByTag("fragmentExpenses");
if (fragment == null) {
fragment = new Expenses();
transaction.replace(R.id.container, fragment, "fragmentExpenses");
transaction.addToBackStack(null);
transaction.commit();
}else{
transaction.remove(getFragmentManager().findFragmentByTag("fragmentExpenses"));
transaction.commit();
fm.popBackStack();
}
break;
default:
break;
}
}
Use this::
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
Fragment fragment = null;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
FragmentManager fm = getFragmentManager();
switch (position) {
case 0:
fragment = fm.findFragmentByTag("fragmentDashboard");
if (fragment == null){
fragment = new Dashboard();
transaction.add(R.id.container, fragment, "fragmentDashboard");
transaction.addToBackStack(null);
transaction.commit();
}else{
transaction.show(getFragmentManager().findFragmentByTag("fragmentDashboard"));
transaction.commit();
fm.popBackStack();
}
break;
case 1:
fragment = fm.findFragmentByTag("fragmentExpenses");
if (fragment == null) {
fragment = new Expenses();
transaction.add(R.id.container, fragment, "fragmentExpenses");
transaction.addToBackStack(null);
transaction.commit();
}else{
transaction.show(getFragmentManager().findFragmentByTag("fragmentExpenses"));
transaction.commit();
fm.popBackStack();
}
break;
default:
break;
}
}
Check Developers site for more info
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 !