I don't understand how to use retain instance on a screen rotation while I am using a TabHost inside a FragmentActivity. I found a lot of things about that, but either talking about to use onRetainNonConfigurationInstance() which is deprecated. Or tu use setRetainInstance(boolean) but FragmentActivity doesn't have this method. Only Fragment have it.
On this link you can find out the code of my main activity:
http://code.google.com/p/musclehackandroid/source/browse/src/com/musclehack/musclehack/MainActivity.java
Thanks in advance,
Cédric
You can use onSavedInstanceState to save the current selected tab:
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt("TAB_POSITION", host.getCurrentTab());
super.onSaveInstanceState(outState);
}
Afterwards you can retrain the selected position in onCreate:
if (savedInstanceState != null) {
host.setCurrentTab(savedInstanceState.getInt("TAB_POSITION"));
}
Well my application is about 5000 lines of code that's why I put the google code git repositery. But I found out a solution!
First, while creating my activity, I check if I was on the tab area I have issue with. If yes I remove all transaction inforamtion.
if(savedInstanceState != null){
int tabPosition = savedInstanceState.getInt("TAB_POSITION");
if(tabPosition == 1){
FragmentManager manager = this.getSupportFragmentManager();
for(int i = 0; i < manager.getBackStackEntryCount(); ++i) {
manager.popBackStack();
}
}
}
Then, here is how I reload all of the fragment registering again the previous corumpted transitions.
TabHost.OnTabChangeListener listener = new TabHost.OnTabChangeListener() {
public void onTabChanged(String tabId) {
Log.d("MainActivity","public void onTabChanged(String tabId) { called");
if(tabId.equals(TAB_A)){
pushFragments(getString(R.string.rss), fragment1rss);
}else if(tabId.equals(TAB_B)){
pushFragments(getString(R.string.worklog), fragment2worklog);
int levelChoice = WorkoutManagerSingleton.getInstance().getLevelChoice();
ListFragment nextFragment = null;
if(levelChoice > 0){
nextFragment = new Fragment2worklog_1subProg();
pushFragmentsRegisterInStack(nextFragment);
}
if(levelChoice > 1){
nextFragment = new Fragment2worklog_2week();
pushFragmentsRegisterInStack(nextFragment);
}
if(levelChoice > 2){
nextFragment = new Fragment2worklog_3day();
pushFragmentsRegisterInStack(nextFragment);
}
if(levelChoice > 3){
nextFragment = new Fragment2worklog_4exercices();
pushFragmentsRegisterInStack(nextFragment);
}
}else if(tabId.equals(TAB_C)){
pushFragments(getString(R.string.testimonials), fragment3testimonials);
}else if(tabId.equals(TAB_D)){
pushFragments(getString(R.string.recipes), fragment4recipe);
}else if(tabId.equals(TAB_E)){
pushFragments(getString(R.string.archives), fragment5archives);
}else if(tabId.equals(TAB_F)){
pushFragments(getString(R.string.book), fragment6book);
}
Log.d("MainActivity","public void onTabChanged(String tabId) { end");
}
};
/*
* adds the fragment to the FrameLayout
*/
public void pushFragments(String tag, Fragment fragment){
FragmentManager manager = this.getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.replace(android.R.id.tabcontent, fragment);
ft.commit();
}
public void pushFragmentsRegisterInStack(Fragment fragment){
FragmentManager manager = this.getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.replace(android.R.id.tabcontent, fragment);
ft.addToBackStack(null);
ft.commit();
}
Related
I want to handle onBackPressed in fragment
I use following code in my activity but this return 0
#Override
public void onBackPressed() {
int count = getFragmentManager().getBackStackEntryCount();
Toast.makeText(getBaseContext(), ""+count, Toast.LENGTH_SHORT).show();
if (count == 1) {
super.onBackPressed();
//additional code
} else {
getFragmentManager().popBackStack();
}
}
Just add .addToBackStack(null) in your Activity or Fragment . When you adding or replacing fragment. Like below
getSupportFragmentManager().beginTransaction().replace(R.id.parent_layout, new MyFragment()).addToBackStack(null).commit();
Note:- you don't have to do anything in your onBackPressed() method.
Just app this line when you want to replace any fragment and manage backsack on Fragment.
ClientHome per = new ClientHome();
Bundle bundle = new Bundle();
bundle.putString("usertype", "client");
per.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_from_left, R.anim.slide_to_right);
fragmentTransaction.replace(R.id.content_frame, per, "tag");
fragmentTransaction.addToBackStack("tag");
fragmentTransaction.commit();
I have an issue with onBackPressed() implementation in my app. I have a single fragment with differents tags. The user could navigate between fragments with a Navigation View and the back button. Everything works as expected except when FragmentTransaction goes like this:
Initial Fragment->A->B->C->A
When I use back button to return, the behavior I want to achieve is A->C->B->Initial.
Instead, I get A->B->C->A->Initial
How can I acomplish my desired behavior?
This is what I have so far:
private int backStackEntries = 0;
public void onBackPressed() {
Log.d(TAG,"Number of fragments in back: "+backStackEntries);
NewsListFragment fragment = (NewsListFragment) getSupportFragmentManager().findFragmentByTag(currentFrag);
backStackEntries-=1;
if(backStackEntries<0)
backStackEntries = 0;
if(fragment.getTag().equals(News_TAG[0])){
if(fragment.getParserMaker().isRunning()){
moveTaskToBack(true);
}
else{
finish();
}
}
else{
currentFrag = getSupportFragmentManager().getBackStackEntryAt(backStackEntries).getName();
getSupportFragmentManager().beginTransaction()
.hide(fragment)
.show(getSupportFragmentManager().findFragmentByTag(currentFrag))
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
}
}
private void makeFragmentTransaction(String[] urls, int item,String _TAG) {
Bundle bundle = new Bundle();
bundle.putStringArray("urls", urls);
NewsListFragment newsFragment = (NewsListFragment) getSupportFragmentManager().findFragmentByTag(_TAG);
if(newsFragment == null){
newsFragment = new NewsListFragment();
}
newsFragment.setArguments(bundle);
if(currentFrag == null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, newsFragment, _TAG)
.addToBackStack(_TAG)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
currentFrag = _TAG;
}
else if(!newsFragment.isAdded()){
getSupportFragmentManager().beginTransaction()
.hide(getSupportFragmentManager().findFragmentByTag(currentFrag))
.add(R.id.container,newsFragment,_TAG)
.addToBackStack(_TAG)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
currentFrag = _TAG;
backStackEntries+=1;
}
else if(!currentFrag.equals(_TAG)){
getSupportFragmentManager().beginTransaction()
.hide(getSupportFragmentManager().findFragmentByTag(currentFrag))
.show(newsFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
backStackEntries+=1;
currentFrag = _TAG;
}
navigationView.setCheckedItem(item);
drawerLayout.closeDrawers();
}
Adding the last backStackEntries+=1; makes the weird behavior and erasing that line makes the deal BUT it creates another Transaction issue:
Initial(going back)->B->C
Pressing back button: C->Initial
I have also tried making transactions like this:
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, newsFragment, _TAG)
.addToBackStack(_TAG)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
currentFrag = _TAG;
And onBackPressed like this:
NewsListFragment fragment = (NewsListFragment) getSupportFragmentManager().findFragmentByTag(currentFrag);
if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
getSupportFragmentManager().popBackStack();
} else {
if (fragment.getParserMaker().isRunning()) {
moveTaskToBack(true);
} else {
finish();
}
}
This also cause the undesired behavior and popBackStack() removes fragment, which I don't want to do.
I also had the same problem, I solved it by implementing my own history stack for the fragments. everytime that I wanted to add a fragment to the stack, I would look through the stack and removed the fragment with the same class as the one I was gonna add (if there was one)
My application had a bottom navigation bar which has 5 tabs.
So according to these tabs, I have 5 fragments
When I click on the tab, the fragment changed according to that tab.
I can switch fragment by using the method beginTransaction().replace...
I dont want the fragment to be destroyed and recreated again each time I switch tabs, so my solution is sth like this
//I init 5 fragments
Fragment1 frag1 = new Fragment1();
Fragment2 frag2 = new Fragment2();
Fragment3 frag3 = new Fragment3();
Fragment4 frag4 = new Fragment4();
Fragment5 frag5 = new Fragment5();
//When I click on tab, for example tab1, I hide all fragments except tab1
//hide all fragments
getSupportFragmentManager()
.beginTransaction()
.hide(fragment1) //Fragment2, 3, 4, 5 as well
.commit();
//show fragment 1
getSupportFragmentManager()
.beginTransaction()
.show(fragment1)
.commit();
It works very well, but the problem is sometimes 2 fragments show at once time (I dont know why because I hide all fragments)
Any other way to achieve that? Switch fragment without destroying it and creating it again.
for adding fragment I make this code for my project, hope it will be help.
public static void replaceFragment(Fragment fragment, FragmentManager fragmentManager) {
String backStateName = fragment.getClass().getName();
String fragmentTag = backStateName;
Fragment currentFrag = fragmentManager.findFragmentById(R.id.frame_container);
Log.e("Current Fragment", "" + currentFrag);
// boolean fragmentPopped = fragmentManager.popBackStackImmediate(backStateName, 0);
int countFrag = fragmentManager.getBackStackEntryCount();
Log.e("Count", "" + countFrag);
if (currentFrag != null && currentFrag.getClass().getName().equalsIgnoreCase(fragment.getClass().getName())) {
return;
}
FragmentTransaction ft = fragmentManager.beginTransaction();
// if (!fragmentPopped) {
ft.replace(R.id.frame_container, fragment);
ft.addToBackStack(backStateName);
ft.commit();
// }
currentFrag = fragmentManager.findFragmentById(R.id.frame_container);
Log.e("Current Fragment", "" + currentFrag);
}
hope this will be help you, and use this method in entire project for replacing fragment.
Using ViewPager with FragmentPagerAdapter suits for you in this case.
Then use ViewPager#setOffsetPageLimit(5). This will help you show/hide your fragments without recreating it again.
Follow this tutorial
Let try it, then tell me if your problem is solved or not. ;)
you don't have to need to hide the fragment just replace the fragment like this method:
public void setFragment(Fragment fragmentWhichYouWantToShow) {
fm = getSupportFragmentManager();
ft = fm.beginTransaction();
ft.replace(R.id.container, fragmentWhichYouWantToShow);
ft.commit();
}
Try to make it in a singe transaction.
protected void showAsRootFragment(Fragment fragment, #NonNull String tag) {
FragmentManager supportFragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = supportFragmentManager.beginTransaction();
if (supportFragmentManager.getFragments() != null) {
for (Fragment attachedFragment : supportFragmentManager.getFragments()) {
if (attachedFragment != null && !tag.equals(attachedFragment.getTag())) {
transaction.hide(attachedFragment);
attachedFragment.setUserVisibleHint(false);
}
}
}
if (!fragment.isAdded()) {
transaction.add(R.id.frame_container, fragment, tag);
fragment.setUserVisibleHint(true);
} else {
transaction.show(fragment);
fragment.setUserVisibleHint(true);
}
transaction.commit();
}
I am trying to use this code
public class TabActivity extends SherlockFragmentActivity implements ActionBar.TabListener, OnItemSelectedListener
{
enum TabType
{
SEARCH, LIST, FAVORITES
}
// Tab back stacks
private HashMap<TabType, Stack<String>> backStacks;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Initialize ActionBar
ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set back stacks
if (savedInstanceState != null)
{
// Read back stacks after orientation change
backStacks = (HashMap<TabType, Stack<String>>) savedInstanceState.getSerializable("stacks");
}
else
{
// Initialize back stacks on first run
backStacks = new HashMap<TabType, Stack<String>>();
backStacks.put(TabType.SEARCH, new Stack<String>());
backStacks.put(TabType.LIST, new Stack<String>());
backStacks.put(TabType.FAVORITES, new Stack<String>());
}
// Create tabs
bar.addTab(bar.newTab().setTag(TabType.SEARCH).setText("Search").setTabListener(this));
bar.addTab(bar.newTab().setTag(TabType.LIST).setText("List").setTabListener(this));
bar.addTab(bar.newTab().setTag(TabType.FAVORITES).setText("Favorites").setTabListener(this));
}
#Override
protected void onResume()
{
super.onResume();
// Select proper stack
Tab tab = getSupportActionBar().getSelectedTab();
Stack<String> backStack = backStacks.get(tab.getTag());
if (! backStack.isEmpty())
{
// Restore topmost fragment (e.g. after application switch)
String tag = backStack.peek();
Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag);
if (fragment.isDetached())
{
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.attach(fragment);
ft.commit();
}
}
}
#Override
protected void onPause()
{
super.onPause();
// Select proper stack
Tab tab = getSupportActionBar().getSelectedTab();
Stack<String> backStack = backStacks.get(tab.getTag());
if (! backStack.isEmpty())
{
// Detach topmost fragment otherwise it will not be correctly displayed
// after orientation change
String tag = backStack.peek();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag);
ft.detach(fragment);
ft.commit();
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
// Restore selected tab
int saved = savedInstanceState.getInt("tab", 0);
if (saved != getSupportActionBar().getSelectedNavigationIndex())
getSupportActionBar().setSelectedNavigationItem(saved);
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
// Save selected tab and all back stacks
outState.putInt("tab", getSupportActionBar().getSelectedNavigationIndex());
outState.putSerializable("stacks", backStacks);
}
#Override
public void onBackPressed()
{
// Select proper stack
Tab tab = getSupportActionBar().getSelectedTab();
Stack<String> backStack = backStacks.get(tab.getTag());
String tag = backStack.pop();
if (backStack.isEmpty())
{
// Let application finish
super.onBackPressed();
}
else
{
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag);
// Animate return to previous fragment
ft.setCustomAnimations(R.anim.slide_from_right, R.anim.slide_to_left);
// Remove topmost fragment from back stack and forget it
ft.remove(fragment);
showFragment(backStack, ft);
ft.commit();
}
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft)
{
// Select proper stack
Stack<String> backStack = backStacks.get(tab.getTag());
if (backStack.isEmpty())
{
// If it is empty instantiate and add initial tab fragment
Fragment fragment;
switch ((TabType) tab.getTag())
{
case SEARCH:
fragment = Fragment.instantiate(this, SearchFragment.class.getName());
break;
case LIST:
fragment = Fragment.instantiate(this, ListFragment.class.getName());
break;
case FAVORITES:
fragment = Fragment.instantiate(this, FavoritesFragment.class.getName());
break;
default:
throw new java.lang.IllegalArgumentException("Unknown tab");
}
addFragment(fragment, backStack, ft);
}
else
{
// Show topmost fragment
showFragment(backStack, ft);
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft)
{
// Select proper stack
Stack<String> backStack = backStacks.get(tab.getTag());
// Get topmost fragment
String tag = backStack.peek();
Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag);
// Detach it
ft.detach(fragment);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft)
{
// Select proper stack
Stack<String> backStack = backStacks.get(tab.getTag());
if (backStack.size() > 1)
ft.setCustomAnimations(R.anim.slide_from_right, R.anim.slide_to_left);
// Clean the stack leaving only initial fragment
while (backStack.size() > 1)
{
// Pop topmost fragment
String tag = backStack.pop();
Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag);
// Remove it
ft.remove(fragment);
}
showFragment(backStack, ft);
}
private void addFragment(Fragment fragment)
{
// Select proper stack
Tab tab = getSupportActionBar().getSelectedTab();
Stack<String> backStack = backStacks.get(tab.getTag());
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Animate transfer to new fragment
ft.setCustomAnimations(R.anim.slide_from_left, R.anim.slide_to_right);
// Get topmost fragment
String tag = backStack.peek();
Fragment top = getSupportFragmentManager().findFragmentByTag(tag);
ft.detach(top);
// Add new fragment
addFragment(fragment, backStack, ft);
ft.commit();
}
private void addFragment(Fragment fragment, Stack<String> backStack, FragmentTransaction ft)
{
// Add fragment to back stack with unique tag
String tag = UUID.randomUUID().toString();
ft.add(android.R.id.content, fragment, tag);
backStack.push(tag);
}
private void showFragment(Stack<String> backStack, FragmentTransaction ft)
{
// Peek topmost fragment from the stack
String tag = backStack.peek();
Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag);
// and attach it
ft.attach(fragment);
}
// The following code shows how to properly open new fragment. It assumes
// that parent fragment calls its activity via interface. This approach
// is described in Android development guidelines.
#Override
public void onItemSelected(String item)
{
ItemFragment fragment = new ItemFragment();
Bundle args = new Bundle();
args.putString("item", item);
fragment.setArguments(args);
addFragment(fragment);
}
}
in my app, doing navigation with tabs. I know, there are used a lot of deprecated methods, but I want to start from this. Everything is working great except when app is getting to background and need to be resumed (after longer time, i think it is cleared from rams). I am getting
java.lang.ClassCastException: java.util.ArrayList cannot be cast to
java.util.Stack
when calling (73 line in code)
Stack backStack = backStacks.get(tab.getTag());
What is wrong? Why its works when activity is starting first time, but onResume it gives ANR?
This is happening I'd say because backStacks.get(tab.getTag()); returns a List not a Stack. Try this instead:
List backStack = backStacks.get(tab.getTag());
You also probably shouldn't be using raw types.
Okey, I found solution by my self. As I find out, there is the problem with HashMap serialization in JAVA, so I saved HashMap as object to cache and when needed - opening it from cache. Everything works as expected.
/**
* In case that there is kinda bug in JAVA serializing HASHMAP, backstacks hashmap is writing to cache as object.
*/
private void serializeBackStack() {
try {
FileOutputStream fos =
new FileOutputStream(getCacheDir() + "backstack.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(backStacks);
oos.close();
fos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* Hashmap with backstacks is getting from object saved in cahse.
*
* #return HashMap
*/
private HashMap<TabType, Stack<String>> deserializeBackStack() {
HashMap<TabType, Stack<String>> map = new HashMap<>();
try {
FileInputStream fis = new FileInputStream(getCacheDir() + "backstack.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
map = (HashMap<TabType, Stack<String>>) ois.readObject();
ois.close();
fis.close();
} catch (IOException ioe) {
ioe.printStackTrace();
return new HashMap<>();
} catch (ClassNotFoundException c) {
c.printStackTrace();
return new HashMap<>();
}
if (map != null)
return map;
else
return new HashMap<>();
}
I currently have a MainActivity.java which should be the only activity class. Though in that activity class I have a nav-drawer which links to other fragment views.
Currently the main issue Im facing is implementing tabs under a fragment and making them just be available for only that fragment and subfragments. I ran my application and the tabs appeared, but they also appear on other fragments after I visit the TeamsAndDriversFragment.
In my MainActivity.java I have the following function which helps point to the fragments it will generate once someone clicks on them in the nav-drawer:
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new TimeAndScoringFragment();
break;
case 1:
fragment = new ScheduleFragment();
break;
case 2:
fragment = new StandingsFragment();
break;
case 3:
fragment = new TeamsAndDriversFragment();
break;
case 4:
fragment = new NewsFragment();
break;
default:
break;
}
if (fragment != null) {
// Create a fragment transaction object to be able to switch fragments
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.frame_container, fragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.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");
}
}
Here is my current TeamsAndDriversFragment class where I have an actionbar navigation with tabs:
public class TeamsAndDriversFragment extends Fragment implements TabListener {
private List<Fragment> fragList = new ArrayList<Fragment>();
#Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
ActionBar bar = getActivity().getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab mTeamsTab = bar.newTab();
mTeamsTab.setText("Teams");
mTeamsTab.setTabListener(this);
bar.addTab(mTeamsTab);
Tab mDriversTab = bar.newTab();
mDriversTab.setText("Drivers");
mDriversTab.setTabListener(this);
bar.addTab(mDriversTab);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Fragment f = null;
TabFragment tf = null;
if(fragList.size() > tab.getPosition()) {
fragList.get(tab.getPosition());
}
if(f == null) {
tf = new TabFragment();
Bundle data = new Bundle();
data.putInt("idx", tab.getPosition());
tf.setArguments(data);
fragList.add(tf);
} else {
tf = (TabFragment) f;
}
ft.replace(android.R.id.content, tf);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if(fragList.size() > tab.getPosition()) {
ft.remove(fragList.get(tab.getPosition()));
}
}
}
In the displayView() method simply remove all tabs from the ActionBar, this way you'll always have a clean ActionBar with the exception of the TeamsAndDriversFragment fragment:
private void displayView(int position) {
getSupportActionBar().removeAllTabs();
// ...
}