I'm attempting to implement a pretty basic navigation structure using Actionbar tabs and fragments. Basically I have three fragments which are selected using the tabs on an actionbar. Each one of these fragments is a listview which should allow the user to select an item and open a detail view.
I'm wondering the best way to add a new fragment to the screen from an existing fragment. I currently have the detail views all implemented as activities (which obviously is not ideal since the action bar tabs aren't there, and navigation using the back button returns to tab 1 regardless of current location).
I'm adding all of the list fragments in my MainActivity;
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (tab.getPosition() == 0) {
Frag1 frag = new Frag1();
ft.replace(android.R.id.content, frag);
} else if (tab.getPosition() == 1) {
Frag2 frag = new Frag2();
ft.replace(android.R.id.content, frag);
} else if (tab.getPosition() == 2) {
Frag3 frag = new Frag3();
ft.replace(android.R.id.content, frag);
}
}
What do I need to implement on those fragments to launch a detail view? I've attempted something like this, but navigation still does not work how I would like it.
private void onListItemClick(View v, int pos, long id) {
Log.d(TAG, "Clicked at position: " + pos);
NewsModel selectedModel = newsItems.get(pos);
Log.d(TAG, "Item: " + selectedModel.getTitle());
NewsDetailFragment fragment = NewsDetailFragment.newInstance(selectedModel);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content, fragment);
ft.addToBackStack(null);
ft.commit();
I'm coming generally from the iOS world so some of my paradigms might be a little out of wack with how Android is meant to function.
Thanks!
As stated in the Supporting Tablets and Handsets training document, the standard way for using Fragments for showing a master/detail view is as separate activities on handsets (when you don't have enough room to show both) and side by side on tablets. The SDK comes with a Master/Detail sample which implements this suggestion (if you are using Eclipse, go to New->Other->Android->Android Activity->Master/Detail Flow).
You can combine this training with the tab code you already have (replacing the left side fragment when tabs are selected, probably also want to remove the detail view on the right hand side when a tab is selected as well) to get a layout that works on all Android devices.
Some additional information you might find useful is Multi-pane layout design guidelines and the entire Fragment Training set.
Related
I am using navigation drawer and it is simple to use. I am not providing the complete code but providing you detail which could be easy for you to understand my problem. I am using fragments these are about 8 in numbers and I am replacing them with one an other. But here comes a problem
I am replacing them on click event of the navigation drawer. but there are two main problems
After replacement , I can see the previous fragment in the background. does replace method just call the new fragment over it ? if yes then what should I do to old fragment not be visible in the background of my new fragment.
When I click navigation drawer Item , it loads the specific fragment successfully. but keeping in that fragment when I click to that specific item again it loads this fragment again and again. For example if drawer item num 3 opens fragment MyBook , then by clicking item num three 2 or many times would open fragment that much time.
So please some one answer me how to cure my app for such kind of actions which I described above.
I tried like this. Its working fine me
FragmentManager frgmanager = getFragmentManager();
frgmanager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
FragmentTransaction frgTransaction = frgmanager.beginTransaction();
if(subitem.equalsIgnoreCase("subitem")){
Frag1 frg1 =new Frag1(mCtx);
frgTransaction.replace(R.id.inflate_layout, frg1);
}else if(subitem1.equalsIgnoreCase("subitem1")){
Frag2 frg2 =new Frag2(mCtx);
frgTransaction.replace(R.id.inflate_layout, frg2);
}else{
Frag2 frg3 =new Frag3(mCtx);
frgTransaction.replace(R.id.inflate_layout, frg3);
}
frgTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
frgTransaction.commit();
you can use addtobackstack in fragmentstranstion object.like
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.bodyfragment, new AnotherFragment());
transaction.addtoBackStack(null).commit();
Use replace-method of FragmentTransaction instead of add (http://developer.android.com/guide/components/fragments.html#Transactions)
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.bodyfragment, new AnotherFragment());
transaction.commit();
To avoid re-instantiating the fragment, keep track of the current open fragment and only do a fragment transaction, if we next-to-be-opened fragment is a different one than the current.
This may achieved like the following:
class MyActivity ... {
private String currentFragment;
private void openNewFragment(Fragment fragment) {
String newFragment = fragment.getClass().getSimpleName();
if (newFragment.equals(currentFragment)){
// new fragment already shown
return;
}
// Fragment transaction etc here:
}
}
Note that this only compares fragments based in their class name. Sometimes this might not be unique, e.g. if there is a DetailFragment class which displays information about an entity. Which entities details to show may depend on intent arguments.
The above code however will then prevent opening DetailFragment for Entity=1 if currently details for Entity=2 are shown. For these scenarios the information about the fragment kept needs to be extended (e.g. storing a Reference or WeakReference to the fragment instance itself).
So basically what I'm working on is very similar to Instagram application, where there're a number of tabs and users can switch to any tab without any delay no matter what there's anything going on, such as refreshing, reloading, and etc. It also uses back button to go back to the previous preserved tab.
In order to achieve this, I've used FragmentManager with FragmentTransaction to show and hide each fragment which represents each tab. I didn't use replace or attach / detach because they destroy view hierarchy of previous tab.
My implementation works pretty well except that showing and hiding fragments are not committed (I highly doubt that this is a right word to say but so far that's how I understood the flow.), or don't occur immediately when SwipeRefreshLayout is refreshing on the fragment (to be hidden) which was added to FragmentManager later than the one to show.
My implementation follows the rules like these. Let's say we have 4 tabs and my MainActivity is showing the first tab, say FirstFragment, and the user selects the second tab, SecondFragment. Because SecondFragment had never been added before, I add it to FragmentManager by using FragmentTransaction.add and hide FirstFragment by using FragmentTransaction.hide. If the user selects the first tab again, because FirstFragment was previously added to FragmentManager, it doesn't add but only show FirstFragment and just hide SecondFragment. And selecting between these two tabs works smoothly.
But when the user "refreshes" SecondFragment's SwipeRefreshLayout and selects the first tab, FragmentTransaction waits for SecondFragment's refresh to be finished and commits(?) the actual transaction. The strange thing is that the transaction is committed immediately the other way around, from FirstFragment's refresh to SecondFragment.
Because this occurs by the order of addition to FragmentManager, I doubt that the order of addition somehow affects backstack of fragments and there might exists something like UI thread priority so that it forces the fragment transaction to be taken place after later-added fragment's UI transition finishes. But I just don't have enough clues to solve the issue. I've tried attach / detach and backstack thing on FragmentTransaction but couldn't solve the issue. I've tried both FragmentTransaction.commit and FragmentTransaction.commitAllowingStateLoss but neither solved the issue.
These are my MainActivity's sample code.
private ArrayList<Integer> mFragmentsStack; // This is simple psuedo-stack which only stores
// the order of fragments stack to collaborate
// when back button is pressed.
private ArrayList<Fragment> mFragmentsList;
#Override
protected void onCreate() {
mFragmentsStack = new ArrayList<>();
mFragmentsList = new ArrayList<>();
mFragmentsList.add(FirstFragment.newInstance());
mFragmentsList.add(SecondFragment.newInstance());
mFragmentsList.add(ThirdFragment.newInstance());
mFragmentsList.add(FourthFragment.newInstance());
mMainTab = (MainTab) findViewById(R.id.main_tab);
mMainTab.setOnMainTabClickListener(this);
int currentTab = DEFAULT_TAB;
mFragmentsStack.add(currentTab);
getSupportFragmentManager().beginTransaction().add(R.id.main_frame_layout,
mFragmentsList.get(currentTab), String.valueOf(currentTab)).commit();
mMainTab.setCurrentTab(currentTab);
}
// This is custom interface.
#Override
public void onTabClick(int oldPosition, int newPosition) {
if (oldPosition != newPosition) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
// First hide the old tab.
fragmentTransaction.hide(mFragmentsList.get(oldPosition));
// Recalculate the fragment stack.
if (mFragmentsStack.contains(newPosition)) {
mFragmentsStack.remove((Integer) newPosition);
}
mFragmentsStack.add(newPosition);
// Add new fragment if it's not added before, or show new fragment which was already hidden.
Fragment fragment = getSupportFragmentManager().findFragmentByTag(String.valueOf(newPosition));
if (fragment != null) {
fragmentTransaction.show(fragment);
} else {
fragmentTransaction.add(R.id.main_frame_layout, mFragmentsList.get(newPosition),
String.valueOf(newPosition));
}
// Commit the transaction.
fragmentTransaction.commitAllowingStateLoss();
}
}
// It mimics the tab behavior of Instagram Android application.
#Override
public void onBackPressed() {
// If there's only one fragment on stack, super.onBackPressed.
// If it's not, then hide the current fragment and show the previous fragment.
int lastIndexOfFragmentsStack = mFragmentsStack.size() - 1;
if (lastIndexOfFragmentsStack - 1 >= 0) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.hide(mFragmentsList.get(mFragmentsStack.get(lastIndexOfFragmentsStack)));
fragmentTransaction.show(mFragmentsList.get(mFragmentsStack.get(lastIndexOfFragmentsStack - 1)));
fragmentTransaction.commitAllowingStateLoss();
mMainTab.setCurrentTab(mFragmentsStack.get(lastIndexOfFragmentsStack - 1));
mFragmentsStack.remove(lastIndexOfFragmentsStack);
} else {
super.onBackPressed();
}
}
Just faced the same issue with only difference - I'm switching fragments on toolbar buttons click.
I've managed to get rid of overlapping fragments overriding onHiddenChanged:
#Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (hidden) {
yourSwipeRefreshLayout.setRefreshing(false);
}
}
Now im into my first question, after not finding an answer in the internet. Usually this should be a really easy thing, but it took me hours and hours so please excuse me if its a beginner question. Also i want to make sure im going the right way before spending more days just to see that in the end it just not works as i want, the way i implement it atm.
The problem:
My App has 3 Tabs with 3 fragments as content, one for every tab. I use Tabs because all users i asked want Tabs and not a Navigation Drawer and i listen to users, not to google (sorry). Also the 3 tabs have very different "roles" (Language Guide, Currency convertor, and own Notebook for own phrases etc) and it makes sense to split it this way (imo). If someone has other ideas, go ahead, im open :-)
The tab-navigation works as intended so far. But now i want to build the further navigation for the single Tabs an im not sure anymore wich way to go... Theres just so many way for a simple thing like this...
The first Tab has some imageButtons to further navigate into this section (See Screenshot 1), to choose a category in the language section. Of course this means the tabs should be stay in place to be able to easy switch to the Converter i.E, just the fragment from tab 1 should get switched to the new fragment (see Screenshot 2), and so on. The Buttons that you see in the below screenshot have clicklisteners that change current fragment to the new one (like "Daily")
For this i open another fragment and add it to the backstack. Maybe you already can guess what happens now. If i press the backbutton, i come back to the first fragment of course. Problems start when i switch tabs when im inside a fragment opened on tab 1. The added fragment is still in backstack what means if i press back button on Tab 2 or 3, the displayed content gets mixes up somehow with the other fragment ones. See Screenshot 3
Do i make an error somehere or can i simply tell the backstack to "reset" when switching tabs so this problem doesnt occur?
Thank you for info and sorry for language and spelling errors, english isnt my main language.
Tablistener Class to switch the tab fragments:
public class MyTabListener implements ActionBar.TabListener {
Fragment fragment;
public MyTabListener(Fragment fragment) {
this.fragment = fragment;
}
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
ft.replace(R.id.fragment_container, fragment);
}
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
ft.remove(fragment);
}
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
// nothing done here
}
}
The Fragments class from first fragment look like this (not full code):
public static class FragmentTab1 extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
final View view = inflater.inflate(R.layout.tab, container, false);
ImageButton catBtn_Daily = (ImageButton) view.findViewById(R.id.catBtn_Daily);
ImageButton catBtn_OnTheRoad = (ImageButton) view.findViewById(R.id.catBtn_OnTheRoad);
ImageButton catBtn_Shopping = (ImageButton) view.findViewById(R.id.catBtn_Shopping);
ImageButton catBtn_Restaurant = (ImageButton) view.findViewById(R.id.catBtn_Restaurant);
ImageButton catBtn_Romance = (ImageButton) view.findViewById(R.id.catBtn_Romance);
ImageButton catBtn_Emergency = (ImageButton) view.findViewById(R.id.catBtn_Emergency);
// attach an OnClickListener
catBtn_Daily.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Create new fragment and transaction
Fragment newFragment = new FragmentTab4();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
transaction.setTransition(4097);
transaction.commit();
}
});
Mainactivity:
public class MainActivity extends Activity {
ActionBar.Tab tab1, tab2, tab3;
Fragment fragmentTab1 = new FragmentTab1();
Fragment fragmentTab2 = new FragmentTab2();
Fragment fragmentTab3 = new FragmentTab3();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab_test);
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
tab1 = actionBar.newTab().setText("Home");
tab2 = actionBar.newTab().setText("Calculator");
tab3 = actionBar.newTab().setText("Notebook");
tab1.setTabListener(new MyTabListener(fragmentTab1));
tab2.setTabListener(new MyTabListener(fragmentTab2));
tab3.setTabListener(new MyTabListener(fragmentTab3));
actionBar.addTab(tab1);
actionBar.addTab(tab2);
actionBar.addTab(tab3);
Cannot post pics yet, rep too low....
Please see here (third pic is called Untitled-3.png)
Screen 1: https://www.dropbox.com/s/3av3pf6a17p2w42/Untitled-1.png
Screen 2: https://www.dropbox.com/s/3av3pf6a17p2w42/Untitled-2.png
Screen 3: https://www.dropbox.com/s/3av3pf6a17p2w42/Untitled-3.png
you might be better off not using the fragment back stack at all. you can maintain your own stack and override onBackPressed() to provide the appropriate behavior.
#Override protected void onBackPressed()
{
if(myStack.isEmpty())
super.onBackPressed(); // default handling finishes the activity
else
{
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, myStack.pop());
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
transaction.commit();
}
}
Actually it sounds like you might want to consider a completely different approach. If I am understanding correctly you might want to consider using a ViewPager with a FragmentPagerAdapter (see the google documentation code sample here: FragmentPagerAdapter).
Essentially the viewpager presents the fragments under your tabs, the adapter provides the list of fragments to show and you select the current "page" by calling setCurrentItem on the viewpager (when the user clicks a tab). Additionally users will be able to swipe between pages (you would update the selected tab by listening to the pager events see google documentation code sample here: ViewPager).
This approach avoids the whole backstack issue and sounds more like what you are after.
Hope it helps.
You can try following:
public void onTabSelected(YourTab tab) {
Fragment fragment = new YourTabFragment();
replaceRootFragment(fragment);
}
public void replaceRootFragment(Fragment fragment) {
if (getSupportFragmentManager().getBackStackEntryCount() != 0) {
int id = getSupportFragmentManager().getBackStackEntryAt(0).getId();
try {
getSupportFragmentManager().popBackStackImmediate(id, FragmentManager.POP_BACK_STACK_INCLUSIVE);
} catch (IllegalStateException e) {
return;
}
}
getSupportFragmentManager().beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.replace(R.id.container, fragment)
.commit();
}
Call onTabSelected when you click on the tab.
I am using a ViewPager in conjunction with ActionBar tabs, as illustrated here. I'm using ActionBarSherlock for backward compatibility, so the parent activity extends SherlockFragmentActivity, and the children fragments extend SherlockFragment.
The solution works great for tabs with swiping, but now I want to dynamically change a fragment associated with one of the tabs.
I've read through numerous S.O. answers on this subject (for example here and here), but I've not found a clear explanation of how to dynamically change a fragment when using ViewPager + the TabsAdapter above.
Here's what I have now. When the user hits a button on an existing fragment, I try to replace the fragment from the parent activity as follows:
AnotherFragment fragment = new AnotherFragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
int viewId = R.id.pager; // resource id of the ViewPager
int position = Constants.TAB_2; // tab pos of the fragment to be changed
String tag = "android:switcher:" + viewId + ":" + position;
ft.replace(viewId, fragment, tag);
ft.commit();
mTabsAdapter.notifyDataSetChanged();
This doesn't work, so I'm missing something. I also tried doing it with nested fragments using getChildFragmentManager(), but ran into a problem since this function isn't available without API 17, Android 4.2.
Thanks for any help!
I've made a little example that shows a similar behaviour. I hope you can reuse it.
I think the key is to use a fragment as a container and replace your "real" fragment using it.
For example, see how to navigate to another fragment:
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction trans = getFragmentManager()
.beginTransaction();
/*
* IMPORTANT: We use the "root frame" defined in
* "root_fragment.xml" as the reference to replace fragment
*/
trans.replace(R.id.root_frame, new SecondFragment());
/*
* IMPORTANT: The following lines allow us to add the fragment
* to the stack and return to it later, by pressing back
*/
trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
trans.addToBackStack(null);
trans.commit();
}
});
You can check the entire example here:
https://github.com/danilao/fragments-viewpager-example
I have an application running a single activity with multiple (2) fragments at a given time. I've got a fragment on the left which functions as a menu for which fragment to
display on the right hand side.
As an example lets say the menu consists of different sports; Football, Basketball, Baseball, Skiing, etc. When the user selects a sport, a fragment with details on the specific sport is displayed to the right.
I've set up my app to display two fragments at once in layout-large and layout-small-landscape. In layout-small-portrait however, only one fragment is displayed at a given time.
Imagine this; a user is browsing the app in layout-small-landscape (two fragments at a time) and selects a sport, Football. Shortly after he selects Basketball. If he now chooses to rotate into layout-small-portrait (one fragment at a time) I want the following to happen:
The Basketball fragment should be visible, but if he presses the back button, he should return to the menu and not to the Football fragment (!) which by default is the previous fragment in the back stack.
I have currently solved this like the following:
....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// static fragments
if(menuFragment == null) menuFragment = new MenuFragment();
if(baseFragment == null) baseFragment = new TimerFragment(); // default content fragment
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
// Determine what layout we're in..
if(app().getLayoutBehavior(this) == LayoutBehavior.SINGLE_FRAGMENT) {
// We are currently in single fragment mode
if(savedInstanceState != null) {
if(!rotateFromSingleToDual) {
// We just changed orientation from dual fragments to single fragment!
// Clear the entire fragment back stack
for(int i=0;i<getSupportFragmentManager().getBackStackEntryCount();i++) {
getSupportFragmentManager().popBackStack();
}
ft.replace(R.id.fragmentOne, menuFragment); // Add menu fragment at the bottom of the stack
ft.replace(R.id.fragmentOne, baseFragment);
ft.addToBackStack(null);
ft.commit();
}
rotateFromSingleToDual = true;
return;
}
rotateFromSingleToDual = true;
ft.replace(R.id.fragmentOne, menuFragment);
} else if(app().getLayoutBehavior(this) == LayoutBehavior.DUAL_FRAGMENTS) {
// We are now in dual fragments mode
if(savedInstanceState != null) {
if(rotateFromSingleToDual) {
// We just changed orientation from single fragment to dual fragments!
ft.replace(R.id.fragmentOne, menuFragment);
ft.replace(R.id.fragmentTwo, baseFragment);
ft.commit();
}
rotateFromSingleToDual = false;
return;
}
rotateFromSingleToDual = false;
ft.replace(R.id.fragmentOne, menuFragment);
ft.replace(R.id.fragmentTwo, baseFragment);
}
ft.commit();
}
This works, at least from time to time. However, many times I get java.lang.IllegalStateException: Fragment already added: MenuFragment (....)
Can anyone please give me some pointers as to how to better implement this? My current code is not pretty at all, and I'm sure many developers out there want to achieve exactly this.
Thanks in advance!
A common way to implement this scenario is to only use the fragment stack when in a mode that shows multiple fragments. When you're in the single fragment mode, you start a new activity that's sole job is to display the single fragment and take advantage of the activity back stack.
In your case you'll just need to remember the currently selected spot on rotate to set it as an argument when starting the new activity.
It's explained much better here:-
http://developer.android.com/guide/components/fragments.html
Hope that helps.