Fragment overlaps sometimes when switching tabs [duplicate] - android

This question already has answers here:
Android: fragments overlapping issue
(17 answers)
Closed 9 years ago.
I have a two pane layout with my buttons on the left. When a button is pressed its corresponding fragment is displayed on the right. Sometimes the fragments overlap but this is an intermittent issue. I can't replicate it all the time but it does happen
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageButtonSettingsManageBooks:
SettingsManageBooksFragment mbFragment = new SettingsManageBooksFragment();
getFragmentManager().beginTransaction().replace(R.id.setting_detail_container2, mbFragment).addToBackStack(null).commit();
mImgFragmentTitle.setImageResource(R.drawable.manage_my_books);
this.getSupportFragmentManager().executePendingTransactions();
break;
case R.id.imageButtonSettingsPurchaseHistory:
SettingsPurchaseHistoryFragment phFragment = new SettingsPurchaseHistoryFragment();
getFragmentManager().beginTransaction().replace(R.id.setting_detail_container2, phFragment).commit();
mImgFragmentTitle.setImageResource(R.drawable.purchase_history);
this.getSupportFragmentManager().executePendingTransactions();
break;
case R.id.imageButtonSettingsAudio:
SettingsAudioFragment aFragment = new SettingsAudioFragment();
getFragmentManager().beginTransaction().replace(R.id.setting_detail_container2, aFragment).commit();
mImgFragmentTitle.setImageResource(R.drawable.audio);
this.getSupportFragmentManager().executePendingTransactions();
break;
case R.id.imageButtonSettingsRestore:
SettingsRestoreFragment rFragment = new SettingsRestoreFragment();
getFragmentManager().beginTransaction().replace(R.id.setting_detail_container2, rFragment).commit();
mImgFragmentTitle.setImageResource(R.drawable.restore);
this.getSupportFragmentManager().executePendingTransactions();
break;
case R.id.imageButtonSettingsCopyright:
SettingsCopyrightFragment cFragment = new SettingsCopyrightFragment();
getFragmentManager().beginTransaction().replace(R.id.setting_detail_container2, cFragment).commit();
mImgFragmentTitle.setImageResource(R.drawable.copyright);
this.getSupportFragmentManager().executePendingTransactions();
break;
case R.id.imageButtonSettingsAbout:
SettingsAboutFragment abFragment = new SettingsAboutFragment();
getFragmentManager().beginTransaction().replace(R.id.setting_detail_container2, abFragment).commit();
mImgFragmentTitle.setImageResource(R.drawable.about);
this.getSupportFragmentManager().executePendingTransactions();
break;
It looks like because I am replacing each fragment with a new fragment that could be causing the overlap. Is there a way to clear all the fragments before committing a new one?

As mentioned by StackOverflowed above this is an intermittent issue. I found a way of fixing this by writing my own code to remove any existing fragments before committing a new one. Below is my code:
fragmentManager = getFragmentManager();
ft = fragmentManager.beginTransaction();
mbFragment = new SettingsManageBooksFragment();
ft.replace(R.id.setting_detail_container2, mbFragment).commit();
mImgFragmentTitle.setImageResource(R.drawable.manage_my_books);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageButtonSettingsManageBooks:
if (mPurchaseHistory == true) {
ft.remove(phFragment);
Log.d(TAG, "REMOVING PURCHASE HISTORY FRAG");
} else if (mAudio == true) {
ft.remove(aFragment);
Log.d(TAG, "REMOVING AUDIO FRAG");
} else if (mRestore == true) {
ft.remove(rFragment);
Log.d(TAG, "REMOVING RESTORE FRAG");
} else if (mCopyright == true) {
ft.remove(cFragment);
Log.d(TAG, "REMOVING COPYRIGHT FRAG");
} else if (mAbout == true) {
ft.remove(abFragment);
Log.d(TAG, "REMOVING ABOUT FRAG");
}
ft = fragmentManager.beginTransaction();
mbFragment = new SettingsManageBooksFragment();
ft.replace(R.id.setting_detail_container2, mbFragment).commit();
mImgFragmentTitle.setImageResource(R.drawable.manage_my_books);
mManageBooks = true;
mPurchaseHistory = false;
mAudio = false;
mRestore = false;
mCopyright = false;
mAbout = false;
break;

Related

save changes of fragment when fragment is replaced

i have implemented Drawer menu in my application. i have 7 different fragments in my app. the MainActivity which holds all the fragments is drawer activity. i have overriden the onBackPressed() method in this activity. i have a fragment where i would like user to save the data he has changed. that is if user have changed something in one fragment and without saving it if user leaves fragment (By selecting another fragment from drawer menu or by pressing a back button) then i want to show the confirmation dialog to user on same fragment where the changes were made. as an example.. if user have made some change in sixth fragment and he leaves the fragment (by selecting any other fragment or back button) i want to show user a confirmation dialog on sixth fragment itself. from where according to his input he can move the selected fragment or stay in the fragment where he made some changes.
Here is the snap of a code of my DrawerActivity.
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis())
{
super.onBackPressed();
AppConstants.SELECTED_NAVIGATION_TAB=0;
return;
}
else { Toast.makeText(getBaseContext(), "Tap back button in order to exit", Toast.LENGTH_SHORT).show(); }
mBackPressed = System.currentTimeMillis();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment = null;
switch (id) {
case R.id.nav_home:
AppConstants.SELECTED_NAVIGATION_TAB = 0;
fragment = new HomeFragment();
title = getResources().getString(R.string.home);
break;
case R.id.nav_progress:
AppConstants.SELECTED_NAVIGATION_TAB = 1;
fragment = new ProgressFragment();
title = getResources().getString(R.string.progress);
break;
case R.id.nav_workouts:
AppConstants.SELECTED_NAVIGATION_TAB = 2;
/* if (Utilities.getInstance().getPreferences(DrawerActivity.this, AppConstants.PREF_KEY_USER_INFO,
AppConstants.PREF_KEY_SUBSCRIPTION_STATUS, "").equals("1")){
fragment = new FragmentPremiumClasses();
title = getResources().getString(R.string.premium);
}else {*/
fragment = new WorkoutsFragment();
title = getResources().getString(R.string.workouts);
// }
break;
case R.id.nav_subscription:
AppConstants.SELECTED_NAVIGATION_TAB = 3;
if (!Utilities.getInstance().getPreferences(DrawerActivity.this, AppConstants.PREF_KEY_USER_INFO,
AppConstants.PREF_KEY_SUBSCRIPTION_STATUS, "").equals("1")){
fragment = new SubscriptionFragment();
title = getResources().getString(R.string.subscription);
} else {
fragment = new SelectSocietyFragment();
title = getResources().getString(R.string.newsubscription);
}
break;
case R.id.nav_aboutUs:
AppConstants.SELECTED_NAVIGATION_TAB = 4;
fragment = new AboutUsFragment();
title = getResources().getString(R.string.aboutus);
break;
case R.id.nav_settings:
AppConstants.SELECTED_NAVIGATION_TAB = 5;
fragment = new SettingsFragment();
title = getResources().getString(R.string.settings);
break;
case R.id.nav_logout:
drawer.closeDrawer(GravityCompat.START);
isLogoutClicked = true;
SharedPreferences.Editor editor = getSharedPreferences(AppConstants.PREF_KEY_USER_INFO,
Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
AppConstants.SELECTED_NAVIGATION_TAB = 0;
Utilities.getInstance().finishAndStartIntent(DrawerActivity.this, MainActivity.class, 0, 0);
break;
}
if (!isLogoutClicked) {
getSupportActionBar().setTitle(title);
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, fragment);
fragmentTransaction.commit();
drawer.closeDrawer(GravityCompat.START);
}
return true;
}
Hope i have made the question clear, how to achieve this functionality? any help would be much appreciated :)
thanks :)
Save data in onPause() of fragment.

onBackPressed closing app in fragments using NavigationDrawer

I'm using NavigationDrawer with some fragments, the problem is when I'm in a fragment and hit the back button, it makes the app close, then I have to open it again, put my username and password all over again to use the app, how can I prevent that from happen?
public class NavigationMain extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...
}
public void setFragmentList(int posicao) {
Fragment fragment = null;
switch (posicao) {
case 0:
fragment = new MainFragment();
break;
case 1:
fragment = new MensagensFragment();
break;
case 2:
fragment = new EscolasFragment();
break;
case 3:
fragment = new AutorizadasFragment();
break;
case 4:
fragment = new CadastroFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
navigationAdapter.resetarCheck();
navigationAdapter.setChecked(posicao, true);
layoutDrawer.closeDrawer(linearDrawer);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
}
#Override
public void onBackPressed() {
int count = getFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
//additional code
} else {
getFragmentManager().popBackStack();
}
}
I think you missed to add the fragment transaction in your back stack. Try the following:
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(null).commit();

Fragment replacing problems

I'm having issues with fragment replacing implementing a navigation drawer.
The problem is layout overlapping, but it happens only if I let the application on the background for a long time (I asume after the activity goes to Stop).
This is the code I'm using for changing fragments. I'm not doing anything in onStop method
(Should I be doing something?)
#Override
public void onNavigationDrawerItemSelected(int position) {
if(lastPosition == position){
return;
}
FragmentTransaction transaction = fragmentManager.beginTransaction();
Fragment lastFragment = fragmentManager.findFragmentByTag( lastTag );
Fragment fragment;
if ( lastFragment != null ) {
transaction.hide( lastFragment );
}
switch (position) {
case 0:
lastTag = "miPerfil";
lastPosition = 0;
fragment = fragmentManager.findFragmentByTag("miPerfil");
if(fragment != null) {
transaction.remove(fragment);
}
transaction.add(R.id.container, MiPerfilFragment.newInstance(position + 1),"miPerfil");
break;
case 1:
lastTag = "misReportes";
lastPosition = 1;
fragment = fragmentManager.findFragmentByTag("misReportes");
if(fragment != null) {
transaction.remove(fragment);
}
transaction.add(R.id.container, MisReportesFragment.newInstance(position + 1),"misReportes");
break;
case 2:
lastTag = "mapFragment";
lastPosition = 2;
fragment = fragmentManager.findFragmentByTag("mapFragment");
if(fragment != null) {
transaction.show(fragment);
}else{
transaction.add(R.id.container, MapFragment.newInstance(position + 1),"mapFragment");
}
break;
case 3:
moveTaskToBack(true);
return;
}
transaction.addToBackStack( lastTag ).commit();
}
Thanks.
there is two solution that you can try to overcome from your problem of overlapping fragment.
try (1) set a background color to your fragment in xml file.
if it does not work,
try (2) fixing this by writing your own code to remove any existing fragments before committing a new one.
for example:
fragmentManager = getFragmentManager();
ft = fragmentManager.beginTransaction();
mbFragment = new SettingsManageBooksFragment();
ft.replace(R.id.setting_detail_container2, mbFragment).commit();
mImgFragmentTitle.setImageResource(R.drawable.manage_my_books);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageButtonSettingsManageBooks:
if (mPurchaseHistory == true) {
ft.remove(phFragment);
Log.d(TAG, "REMOVING PURCHASE HISTORY FRAG");
} else if (mAudio == true) {
ft.remove(aFragment);
Log.d(TAG, "REMOVING AUDIO FRAG");
} else if (mRestore == true) {
ft.remove(rFragment);
Log.d(TAG, "REMOVING RESTORE FRAG");
} else if (mCopyright == true) {
ft.remove(cFragment);
Log.d(TAG, "REMOVING COPYRIGHT FRAG");
} else if (mAbout == true) {
ft.remove(abFragment);
Log.d(TAG, "REMOVING ABOUT FRAG");
}
ft = fragmentManager.beginTransaction();
mbFragment = new SettingsManageBooksFragment();
ft.replace(R.id.setting_detail_container2, mbFragment).commit();
mImgFragmentTitle.setImageResource(R.drawable.manage_my_books);
mManageBooks = true;
mPurchaseHistory = false;
mAudio = false;
mRestore = false;
mCopyright = false;
mAbout = false;
break;
hope it will helps....
if you use first solution You may also come up with problems where the fragment behind your new fragment is still clickable. If this happens then just make the parent view of the new fragment clickable..

How to keep only one instance of a fragment, when switching with NavigationDrawer?

My App starts with a AddressFragment. From the NavigationDrawer I start (amongst others) a new AddressFragment with:
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new AddressFragment())
.addToBackStack(null)
.commit();
But I would rather just go back the first instance. How could I do that?
Or more general, how can I find out, whether an instance of a fragment already exists and then start that, if yes, otherwise create one?
When creating the fragment set a tag for it, then later you can find it through the fragment manager and replace/create accordingly.
FragmentManager fManager = getFragmentManager();
FragmentTransaction fTransaction = fManager.beginTransaction();
Fragment fragment = fManager.findFragmentByTag("uniqueTag");
// If fragment doesn't exist yet, create one
if (fragment == null) {
fTransaction.add(R.id.fragment_list, new ListFrag(), "uniqueTag");
}
else { // re-use the old fragment
fTransaction.replace(R.id.fragment_list, fragment, "uniqueTag");
}
Step one:
Optimize current code to allow a Fragment to have his own "TAG"
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new AddressFragment())
.addToBackStack(**AddressFragment.class.getName()**)
.commit();
Step two:
Somewhere in your application flow you will need to determine if a fragment exists:
public static boolean isFragmentInBackstack(final FragmentManager fragmentManager, final String fragmentTagName) {
for (int entry = 0; entry < fragmentManager.getBackStackEntryCount(); entry++) {
if (fragmentTagName.equals(fragmentManager.getBackStackEntryAt(entry).getName())) {
return true;
}
}
return false;
}
Step three:
perform fragment action
if (exists) {
// Fragment exists, go back to that fragment
//// you can also use POP_BACK_STACK_INCLUSIVE flag, depending on flow
mFragmentManager.popBackStackImmediate(AddressFragment.class.getName(), 0);
} else {
// Fragment doesn't exist
// STEP 1 + additional backstack management
}
This is tested answer, Hope this will help you
First Make these field globally in MainActivity
private static final int TIME_INTERVAL = 2000;
private long mBackPressed;
private FragmentManager fm;
private FragmentTransaction ft;
private DrawerLayout drawer;
Now in onNavigationItemSelected() implement like that
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Fragment fragment = null;
Class fragmentClass = null;
switch (item.getItemId()) {
case R.id.nav_home:
fragmentClass = Fragment.class;//this is MainAvctivty extends AppCompatActivity
break;
case R.id.nav_f1:
fragmentClass = FragmentOne.class;
break;
case R.id.nav_f2:
fragmentClass = FragmentTwo.class;
break;
case R.id.nav_f3:
fragmentClass = FragmentThree.class;
break;
case R.id.nav_f4:
fragmentClass = FragmentFour.class;
break;
case R.id.nav_f5:
fragmentClass = FragmentFive.class;
break;
default:
fragmentClass = Fragment.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {e.printStackTrace();}
//Insert the fragment by replacing any existing fragment
fm = getSupportFragmentManager();
ft = fm.beginTransaction();
ft.replace(R.id.frame_container, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
item.setChecked(true);
setTitle(item.getTitle());
drawer.closeDrawers();
return true;
}
Now handle onbackpressed like below
#Override
public void onBackPressed() {
if (drawer != null) {
fm = getSupportFragmentManager();
ft = fm.beginTransaction();
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
ft.commit();
} else if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis()) {
super.onBackPressed();
} else {
Toast.makeText(this,"Press again to exit the app",Toast.LENGTH_SHORT).show();
}
mBackPressed = System.currentTimeMillis();
}
}
First time you create the fragment with a tag.
When you want to replace it try to get the fragment with tag and if it return null you create a new one

Switching fragments in Sliding Menu?

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 !

Categories

Resources