So, I have a primary activity with a fragment (FragmentA) set as default.
I have two buttons in my toolbar;
Button 1 rotates the screen and sets FragmentA's layout to landscape
Button 2 should replace FragmentA with a new FragmentB.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.split_screen) {
currentFragment = new DualScreenFragment();
toggleSplitScreen();
}
else if (id == R.id.rotate_screen) {
currentFragment = new PrimaryPDFFragment();
toggleScreenOrientation();
}
return super.onOptionsItemSelected(item);
}
toggleSplitScreen():
private void toggleSplitScreen() {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.target_pane, currentFragment);
transaction.commit();
if (getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
toggleScreenOrientation():
private void toggleScreenOrientation() {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
However, I cant seem to handle the replacing and rotation all in one. I have to press the split screen button one to enter landscape mode and then a second time to actually replace the fragment.
Any idea as to how I can fix this?
use this code
// Create new fragment and transaction
Fragment newFragment = new BlankFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
Related
When i change tab of Bottom Bar for example when the home tab is selected and when i change the tab and select category tab in first time load data and it is not problem but when select again home tab again reload fragment and load data again.
how to resolve this problem and save state fragment.
My code:
bottomBar.setOnTabSelectListener(new OnTabSelectListener() {
#Override
public void onTabSelected(int tabId) {
displayFragment(tabId);
}
});
private void displayFragment(int id) {
Fragment selectedFragment = null;
switch (id) {
case R.id.tab_home:
selectedFragment = HomeFragment.getInstance();
break;
case R.id.tab_category:
selectedFragment = CategoryFragment.getInstace();
break;
}
if (selectedFragment != null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.contentContainer, selectedFragment);
transaction.commit();
}
}
There are multiple ways you can handle preserving and updating your fragments data throughout its life cycle. I would look into the lifecycle of activity fragments to better grasp what applies to your context. From 30k feet, after you call .replace() the fragment's override onCreateView() should fire, here you can handle your update logic.
As I mentioned, context is big here. If you end up changing your transaction logic, it could impact the life cycle of your fragments. For example, if you were hiding/showing your fragments, using the override onHidden() or onResume() could be a better solution.
In addition, you also should consider how your navigation logic impacts and interacts with your activity's/fragment's backstack. In your current logic, you're creating a new instance of the fragment each time a tab is selected.
This is answer my question :
public class MainActivity extends AppCompatActivity {
FeedFragment feedFragment;
PublishFragment publishFragment;
ServicesFragment servicesFragment;
SearchFragment searchFragment;
ProfileFragment profileFragment;
FragmentTransaction ft;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomBar bottomBar = (BottomBar) findViewById(R.id.bottomBar);
feedFragment = new FeedFragment();
publishFragment = new PublishFragment();
servicesFragment = new ServicesFragment();
searchFragment = new SearchFragment();
profileFragment = new ProfileFragment();
bottomBar.setOnTabSelectListener(new OnTabSelectListener() {
#Override
public void onTabSelected(#IdRes int tabId) {
if (tabId == R.id.feed_icon) {
GeneralUtils.logPrint("feed");
ft = getSupportFragmentManager().beginTransaction();
if (feedFragment.isAdded()) {
ft.show(feedFragment);
} else {
ft.add(R.id.fragment_container, feedFragment);
}
hideFragment(ft,publishFragment);
hideFragment(ft, servicesFragment);
hideFragment(ft,searchFragment);
hideFragment(ft,profileFragment);
ft.commit();
}
if (tabId == R.id.publish_icon) {
GeneralUtils.logPrint("publish");
ft = getSupportFragmentManager().beginTransaction();
if (publishFragment.isAdded()) {
ft.show(publishFragment);
} else {
ft.add(R.id.fragment_container, publishFragment);
}
hideFragment(ft,feedFragment);
hideFragment(ft, servicesFragment);
hideFragment(ft,searchFragment);
hideFragment(ft,profileFragment);
ft.commit();
}
if (tabId == R.id.services_icon) {
GeneralUtils.logPrint("services");
ft = getSupportFragmentManager().beginTransaction();
if (servicesFragment.isAdded()) {
ft.show(servicesFragment);
} else {
ft.add(R.id.fragment_container, servicesFragment);
}
hideFragment(ft,feedFragment);
hideFragment(ft, publishFragment);
hideFragment(ft,searchFragment);
hideFragment(ft,profileFragment);
ft.commit();
}
if (tabId == R.id.search_icon) {
GeneralUtils.logPrint("search");
ft = getSupportFragmentManager().beginTransaction();
if (searchFragment.isAdded()) {
ft.show(searchFragment);
} else {
ft.add(R.id.fragment_container, searchFragment);
}
hideFragment(ft,feedFragment);
hideFragment(ft,publishFragment);
hideFragment(ft,servicesFragment);
hideFragment(ft,profileFragment);
ft.commit();
}
if (tabId == R.id.profile_icon) {
GeneralUtils.logPrint("profile");
ft = getSupportFragmentManager().beginTransaction();
if (profileFragment.isAdded()) {
ft.show(profileFragment);
} else {
ft.add(R.id.fragment_container, profileFragment);
}
hideFragment(ft,feedFragment);
hideFragment(ft, publishFragment);
hideFragment(ft,servicesFragment);
hideFragment(ft,searchFragment);
ft.commit();
}
}
});
}
private void hideFragment(FragmentTransaction ft, Fragment f) {
if (f.isAdded()) {
ft.hide(f);
}
}
}
From my main activity, pressing Settings button opens an AppCompatActivity with FrameLayout as the container for the fragments. In OnCreate method, I'm adding the fragment which is a PreferenceScreen container.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
Toolbar toolbar = (Toolbar) findViewById(R.id.custom_toolbar);
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
if (ab != null) {
ab.setDisplayHomeAsUpEnabled(true);
ab.setTitle("Settings");
}
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = null;
if (savedInstanceState == null) {
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragment = SettingsFragment.newInstance(null);
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
}
Pressing again another button called Options, opens replaces fragment with Options fragment adding the current class to backstack.
#Override
public boolean onPreferenceStartScreen(PreferenceFragmentCompat caller, PreferenceScreen pref) {
FragmentManager manager = getSupportFragmentManager();
SettingsSubscreenFragment fragment = null;
Bundle args = new Bundle();
switch (pref.getKey()) {
case "pref_key_rejection_options":
getSupportActionBar().setTitle("Rejection Options");
fragment = SettingsSubscreenFragment.newInstance("Options");
break;
}
args.putString(PreferenceFragmentCompat.ARG_PREFERENCE_ROOT, pref.getKey());
if (fragment != null) {
fragment.setArguments(args);
}
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.fragment_container, fragment, pref.getKey());
ft.addToBackStack(null);
ft.commit();
return true;
}
When I press the Up Button, I'm just replacing the Options fragment to the first fragment, Settings, which does not pop the back stack.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getSupportActionBar().setTitle("Settings");
FragmentManager fragmentManager;
FragmentTransaction ft;
Fragment fragment = null;
if (getSupportFragmentManager().findFragmentByTag("pref_key_options") != null) {
fragmentManager = getSupportFragmentManager();
ft = fragmentManager.beginTransaction();
fragment = SettingsFragment.newInstance(null);
ft.replace(R.id.fragment_container, fragment);
ft.commit();
fragmentManager.getFragments().clear();
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
return super.onOptionsItemSelected(item);
}
So, opening the Options fragment again will add another to back stack and onBackPress, it only pops the topmost and leaves its shadow overlapping the other one registered in back stack.
#Override
public void onBackPressed() {
int backStackCount = getSupportFragmentManager().getBackStackEntryCount();
if (backStackCount >= 1) {
getSupportActionBar().setTitle("Settings");
getSupportFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
The almost the same situation is like from here, third picture of the question, but I can't make it work with their suggestions.
What am I doing wrong and what I can do to make this work? Thanks a lot.
Check FragmentTransaction , SettingsSubscreenFragment and SettingsFragmentare extending android.support.v4.app.Fragment . If not , try
class YourFragments extends android.support.v4.app.Fragment
in your fragment classes.
Recently i'm working on my app to make it load faster and work better, i'm using navigation drawer in my MainActivity:
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camara) {
LoadJson asyncTask = (LoadJson) new LoadJson(new LoadJson.AsyncResponse() {
#Override
public void processFinish(JSONArray output) {
//Here you will receive the result fired from async class
//of onPostExecute(result) method.
//Set the fragment initially
MainFragment fragment = new MainFragment(output);
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
// Handle the camera action
}
}).execute();
} else if (id == R.id.nav_gallery) {
//Set the fragment initially
GalleryFragment fragment = new GalleryFragment();
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_search) {
//Set the fragment initially
FetchResualt fragment = new FetchResualt();
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
// Handle the camera action
} else if (id == R.id.nav_manage) {//
Bundle bundle = new Bundle();//
bundle.putInt("someStr",ID_OF_BEACH);//
//Set the fragment initially//
FragmentBeach fragment = new FragmentBeach();//
fragment.setArguments(bundle);//
FragmentTransaction fragmentTransaction =//
getSupportFragmentManager().beginTransaction();//
fragmentTransaction.replace(R.id.fragment_container, fragment);//
fragmentTransaction.commit();//
// Handle the camera action
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
As you can see if we push the first menu if (id == R.id.nav_camara) it will pass a JSONArray to a Fragment class and it take like 4-5 seconds to load. So if the user navigates between menus every time he goes to nav_camara it make the app a 4 second freeze to load and as you can see everytime we choose a menu item it will recreate a new copy of fragment, so even if I make: setRetainInstance(true); in my fragment class it wont work.
What solution you suggest to prevent the app to recreate a new fragment each time we choose a menu item?
You will need to keep a SparseArray<Fragment> to keep the instances in memory.
Follow these steps:
create a field in your Activity:
SparseArray<Fragment> myFragments;
initialise it in the onCreate() like:
myFragments = new SparseArray<Fragment>();
update your onNavigationItemSelected():
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camara) {
// get cached instance of the fragment
fragment = myFragments.get(INT_CONSTANT_FOR_CAM_FRAGMENT);
// if fragment doesn't exist in myFragments, create one and add to it
if (fragment == null) {
fragment = new MainFragment();
myFragments.put(INT_CONSTANT_FOR_CAM_FRAGMENT, fragment);
}
// now load the fragment
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
// do the rest with others as well.
}
move the AsyncTask thing inside your MainFragment's onActivityCreated() or a similar lifecycle method.
Above way will let you reuse the fragments and move the logic to their correct location (your Activity shouldn't know how MainFragment loads data to initiate itself, but of course you can still keep it there, though not recommended).
You can add a TAG while push a new fragment to the container. Then use FragmentManager#findFragmentByTag to find any fragment previously added with the same tag.
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Fragment oldFragment = manager.findFragmentByTag(tag);
if (oldFragment != null)
transaction.replace(R.id.fragment_container, oldFragment, tag);
else
transaction.replace(R.id.fragment_container, newInstanceOfFragment, tag);
transaction.commit();
Declare them globally
GalleryFragment galleryFrag = new GalleryFragment();
FragmentTransaction ft;
FragmentManager fm;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
fm = getSupportFragmentManager();
...
}
then on your navigation selection
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_search) {
ft = fm.beginTransaction();
ft.replace(R.id.fragment_container, galleryFrag).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
I have a fragment activity from where i can start my fragments which contain a viewpager. In my fragment activity I have added this piece of code.
fragment = new ItemPagerFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.content_frame, fragment);
transaction.addToBackStack(null);
transaction.commit();
Now when I press back button only blank screen appears and it does not lead me to my fragment activity.
What wrong i might be doing?
Use this in activity that holds fragment.
#Override
public void onBackPressed() {
if (fragmentManager.getBackStackEntryCount() > 1) {
fragmentManager.popBackStack();
} else
finish();
}
Try this way,
// Create new fragment and transaction
Fragment newFragment = new ItemPagerFragment();
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
Modify your code
#Override
public void onBackPressed() {
if(some condition) {
// do something
} else {
super.onBackPressed();
}
}
Please follow this link
Handling back button press Inside Fragments
You have to tell to the fragment manager that the back button was pressed. Override onBackPressed on your Activity
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() == 0) {
super.onBackPressed();
} else {
getFragmentManager().popBackStack();
}
}
private void changeFragment (Fragment fragment){
String backStackName = fragment.getClass().getName();
FragmentManager manager = getSupportFragmentManager();
boolean fragmentPopped = manager.popBackStackImmediate (backStackName, 0);
if (!fragmentPopped){ //fragment not in back stack, create it.
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(backStackName );
ft.commit();
}
}
While launching fragment assign a TAG to each fragment.When you want to back press check the existence of an fragment using assigned TAG name and then do corresponding action.for example:
private final static String TAG_FRAGMENT = "TAG_FRAGMENT";
//when want to add fragment to view
private void showFragment() {
final Myfragment fragment = new MyFragment();
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment, fragment, TAG_FRAGMENT);
transaction.addToBackStack(null);
transaction.commit();
}
//in activity back pressed check the existence of fragment by TAG
#Override
public void onBackPressed() {
final Myfragment fragment = (Myfragment) getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);
if (fragment.allowBackPressed()) { // and then you define a method allowBackPressed with the logic to allow back pressed or not
super.onBackPressed();
}
}
I am using a navigation drawer.So when my application starts i am calling the homeFragment and keeping it in the backstack. Now if the user selects any options from the navigation drawer i am opening the respective fragment but without adding them to backstack. So what i want is that even when user has open 10 fragment, on pressing back they should be taken back to homeFragment only. But with my code the app exits on pressing back even homeFragment is in the backstack.
Code to openFragments
public static void replaceFragment(FragmentActivity activity, Fragment fragment, boolean addToBackStack) {
try {
String backStateName = fragment.getClass().getName();
String fragmentTag = backStateName;
FragmentManager manager = activity.getSupportFragmentManager();
boolean fragmentPopped = manager.popBackStackImmediate(fragmentTag, 0);
if (!fragmentPopped && manager.findFragmentByTag(fragmentTag) == null) {
FragmentTransaction ft = manager.beginTransaction();
ft.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right);
ft.replace(R.id.frag_container, fragment, fragmentTag);
if (addToBackStack) {
ft.addToBackStack(backStateName);
}
ft.commit();
}
} catch (Exception e) {
e.printStackTrace();
}
}
From MainActivity
private void init() {
setUpToolBar();
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerFrag = (NavigationDrawerFrag) getSupportFragmentManager().findFragmentById(R.id.frag_nav_drawer);
drawerFrag.setUp(drawerLayout, toolbar, R.id.frag_nav_drawer);
CommonFunctions.replaceFragment(this, new HomeFrag(), true);
}
On NavigationDrawer Item click
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 1) {
CommonFunctions.replaceFragment(getActivity(), new ProfileFrag(), false);
} else if (position == 2) {
CommonFunctions.replaceFragment(getActivity(), new CelebrityFrag(), false);
} else if (position == 4) {
CommonFunctions.replaceFragment(getActivity(), new AboutUsFrag(), false);
} else if (position == 5) {
CommonFunctions.replaceFragment(getActivity(), new TermsAndConditions(), false);
}
lvNavItems.setItemChecked(position, true);
//lvNavItems.setSelection(position);
lvNavItems.setSelected(true);
mDrawerLayout.closeDrawer(fragContainer);
}
Add onBackPressed() method in activity to check backstack and if entry is more then zero so call popbackstack method.
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() != 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
//Put this in your onNavigationItemSelected of MainActivity
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
//FrameLayout where you load your home fragment tools:layout="#layout/frag_home"
ft.replace(R.id.content_frame,nav_selected);
if(getSupportFragmentManager().getBackStackEntryCount() != 0){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
getSupportFragmentManager().popBackStack();
}
//Don't add Home screen
if(id != R.id.nav_home){
ft.addToBackStack(null);
}
ft.commit();