I've never used Fragments before but now I have a PlayerStatus fragment, that I want to use in two different activities. It shows player status:
public class PlayerStatus extends Fragment {
Player player;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.player_status, container, false);
return view;
}
public void setPlayer(Player player) {
this.player = player;
}
}
Fragment's layout looks like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical"
android:paddingTop="0dp" >
<include
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
layout="#layout/money" />
<include
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
layout="#layout/wins" />
<include
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
layout="#layout/level" />
</LinearLayout>
I get it in the activity this way:
#Override
protected void onResume() {
super.onResume();
setContentView(R.layout.game);
fPlayerStatus = (PlayerStatus) getFragmentManager().findFragmentById(R.id.fPlayerStatus);
fPlayerStatus always returns null.
What am I doing wrong?
Read about how to start fragments ,attach/detach from activity , what does commit() do and there are few more basic functions which you should know when using fragments
http://developer.android.com/guide/components/fragments.html
Fragment Basics Tutorial
go through these web sites and you'll definately get through with fragments easily .
To make your fragments work here you have to do the following :
1.Add your fragment to your activity
write the following
FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.YOUR_FRAGMENT_ID_AS_DEFINED_IN_XML , object of your fragment class)
fragmentTransaction.commit();
____________END----------------------------------
There are many other useful methods in the APIs from FragmentTransaction , read them through the link above and you'll be abel to use them easily
Lemme know if it helped.
Your fragment has not been added to the FragmentManager in your Activity.
First do a FragmentTransaction with beginTransaction().add(...) on the getFragmentManager().
And don't forget to commit() it.
I don't Think you can use one Fragment for two Activities.
As i think your approach should be
Step 1
Create two fragment Layouts in your Activity_main
Step 2
then use fragment manager in your activity like below
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.frame,fragment)
fragmentTransaction.commit();
Related
I am new to developing android applications, so please pardon any stupid mistakes that I may have made. On to the question:
I am making an application which has its main activity layout screen containing some stuff and have a navigation drawer wired in. Now I am trying to use the entries in the navigation drawer to call up various fragments and display them over my main activity. However when I run my piece of code, I am getting an Activity Destroyed error I have attached my code below for reference. I think the problem is with what I have done with the container. To make the fragment cover the whole screen of my main activity, I gave the fragment container as the root layout as I was unsure how to go about this.
Code which handles item clicks from navigation drawer
class DrawerItemClickListener extends FragmentActivity implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
private void selectItem(int position) {
Fragment mFragment = null;
switch(position) {
case 0:
mFragment = new AnnouncementFragment();
Bundle args = new Bundle();
args.putInt(null, position);
break;
case 1:
break;
case 2:
break;
case 3:
break;
default:
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction().replace(R.id.drawer_layout, mFragment);
transaction.commit();
transaction.addToBackStack(null);
}
Code for fragment
public class AnnouncementFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_announcement, container, false);
}
XML layout of main activity
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id = "#+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/screen_login"
android:gravity="center"
android:textColor="#android:color/holo_blue_light"
android:id="#+id/login_tv"
android:layout_alignParentTop="true"
android:layout_marginTop="105dp"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"
android:textSize="40sp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/username_et"
android:layout_below="#id/login_tv"
android:layout_alignParentStart="true"
android:layout_marginTop="45dp"
android:layout_alignParentEnd="true"
android:hint="#string/username"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/editText2"
android:layout_below="#id/username_et"
android:layout_alignParentStart="true"
android:layout_marginTop="30dp"
android:layout_alignParentEnd="true"
android:hint="#string/password" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/login"
android:id="#+id/login_btn"
android:layout_below="#+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp" />
</RelativeLayout>
<ListView
android:id="#+id/drawer_list"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#ffeeeeee"/>
Error
java.lang.IllegalStateException: Activity has been destroyed
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1399)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:637)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:616)
at com.it.learnera.DrawerItemClickListener.selectItem(DrawerItemClickListener.java:40)
at com.it.learnera.DrawerItemClickListener.onItemClick(DrawerItemClickListener.java:19)
I am wondering how I can make the fragment draw over the main activity layout without causing a mess
Cheers and Thanks in advance
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction()
.replace(R.id.drawer_layout, mFragment); // < - first problem ( see ad. 1)
.commit() // <- third problem (see ad. 3)
// second problem ( see ad. 2)
mFragment = new AnnouncementFragment();
Bundle args = new Bundle();
args.putInt(null, position);
ad 1. You replacing DrawerLayout instead of its container
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
drawer_layou - this is a view which holds:
FrameLayout / with id - >content_frame
( container capable to hold "only" one element: fragment / view)
ListView / with id - > left_drawer
( list view for example with menu entries )
so you need replace content_frame
ps to better see purpose of transaction you should call it in one statement - in "chain / sequence "
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frame_layout, mFragment)
.addToBackStack(null) // add to manager " will remember this fragment - for navigation purpose"
.commit() // commit mean do everything from top to bottom on next pass
ad 2. you need also put args in fragment:
mFragment = new AnnouncementFragment();
Bundle args = new Bundle();
args.putInt(null, position);
mFragment.setArguments(args)
ad 3. You calling commit when activity is after onSaveInstanceState
Note:
A fragment transaction can only be created/committed prior to an activity saving its state.
If you try to commit a transaction after:
Activity.onSaveInstanceState()
and prior to a following
Activity.onStart()
Activity.onResume()
you will get an error. This is because the framework takes care of saving your current fragments in the state, and if changes are made after the state is saved then they will be lost.
After FragmentTransaction is committed with FragmentTransaction.commit() is scheduled to be executed asynchronously on the process's main thread.
If you want to immediately executing any such pending operations, you can call this function (only from the main thread) to do so. Note that all callbacks and other related behavior will be done from within this call, so be careful about where this is called from.
boolean executePendingTransactions();
which return true if there were any pending transactions to be executed.
btw look at this docs which refers to extending an FragmentActivity:
https://developer.android.com/reference/android/support/v4/app/FragmentActivity.html
i don't know which api you target but you may also check this bug:
http://johnfeng.github.io/blog/2015/05/31/fragment-activity-has-been-destoryed-problem/
( problem with child fragment which state is not being reset )
Hi, appreciate the detailed explanation but it doesnt work – Prejith P
and this article about state loss which is i think related to your problem
http://www.androiddesignpatterns.com/2013/08/fragment-transaction-commit-state-loss.html
so you can try call instead of commit() (but this is not solution):
commitAllowingStateLoss()
Hi, I fixed it myself just now. I changed the implementation of my navigation drawer a bit and it just started working. I have no idea how it got fixed, which is why I haven't posted an answer here – Prejith P
YES - the problem was your implementation you have tried to call commit() after an activity instance was destroyed what is indicating by stack trace
java.lang.IllegalStateException: Activity has been destroyed
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1399)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:637)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:616)
at com.it.learnera.DrawerItemClickListener.selectItem(DrawerItemClickListener.java:40)
at com.it.learnera.DrawerItemClickListener.onItemClick(DrawerItemClickListener.java:19)
`
when You call commit() you should ensure that:
activity is attached
activity is visible ( before onSaveInstanceState )
The problem is that you're calling transaction.addToBackStack(null); after you commit the replacement. I suggest you to do as follow:
getSupportFragmentManager().beginTransaction()
.replace(R.id.drawer_layout, mFragment).addToBackStack(null).apply();
u need a fragment to fragment communication
class DetailActivity extends
AppCompatActivity implements BioDetailClickView {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.navigation);
setSupportActionBar(toolbar);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null) {
fragment = new Fragment1();
fm.beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
}
}
public void fragment_transaction(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
#Override
public void onClickFragmentQuick() {
Fragment frag= new Fragment1();
fragment_transaction(frag);
}
#Override
public void onClickFragment2() {
Fragment fragment =new Fragment2();
fragment_transaction(fragment);
}
#Override
public void onClickFragment3() {
Fragment fragment =new Fragment3();
fragment_transaction(fragment);
}
public interface BioDetailClickView {
void onClickFragment1();
void onClickFragment2();
void onClickFragment3();
}
Basically this question has been asked many of times here and here.Solution given is not working for me. In some corrent answers were not posted by user.
I want to have nested fragments. My scenario is as below :
I have one MainActivity, ProductEnterFrag, and ProductListFrag,ProductDetailFrag.
I have add the ProductEnterFrag to MainActivity dynamically by the FragmentManager. Like this :
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.container, new ProductEnterFrag());
ft.commit();
ProductEnter layout is as below :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
I have added the ProductListFrag to ProductEnterFrag like this :
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ProductListFrag(new ProductListFrag());
}
public void ProductListFrag(SherlockFragment frag) {
getChildFragmentManager().beginTransaction().add(R.id.fragContainer, frag).commit();
getChildFragmentManager().executePendingTransactions();`
}
ProductListFrag whose layout is, as below :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="product1" />
</LinearLayout>
Now on click of button, I want to add a another fragment say ProductDetailFrag,which should be another child fragment.
When I am trying to add ProductDetailFrag from ProductListFrag like this :
new ProductEnterFrag().ProductListFrag(new ProductDetailsFrag());
It is throwing me : java.lang.IllegalStateException: Activity has been destroyed
I am new in nested fragments. Please help me where I am doing wrong. I have stuck with this problem from last 2 days.
I am trying to show multiple fragments on the one screen by creating them programmatically. I am able to do this no problem by including each fragment into the activities layout file. However when I try and do it programmatically Im confused.This is what I have so far for two fragments on a screen.
Main Class:
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentOne one = new FragmentOne();
FragmentTwo two = new FragmentTwo();
FragmentThree three = new FragmentThree();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.imOne, one, "fragmentone");
ft.add(R.id.imTwo, two, "fragmenttwo");
ft.add(R.id.imThree, three, "fragmenthree");
ft.commit();
}
}
Fragment One:
public class FragmentOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.frag_one, container, false);
return view;
}
}
Fragment Two:
public class FragmentTwo extends Fragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.frag_two, container, false);
return view;
}
}
The layout files for my two fragment classes just contain a simple TextView.
And then the activity_main.xml layout file for my main class:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<FrameLayout
android:id="#+id/imOne"
android:name="com.david.twofragexample.FragmentOne"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2" />
<FrameLayout
android:id="#+id/imTwo"
android:name="com.david.twofragexample.FragmentTwo"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2" />
<FrameLayout
android:id="#+id/imThree"
android:name="com.david.twofragexample.FragmentThree"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2" />
</LinearLayout>
When I try and do it programatically I get confused as to what should be in my activity_main.xml file. So from the Android Developer Guide(http://developer.android.com/guide/components/fragments.html) it says to use
FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FragmentOne fragment = new FragmentOne();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
So when I add this code to my onCreate method what changes do I have to make to my activity_main.xml file to do this programmatically?I don't see where R.id.fragment_container comes from. How can I determine where on the screen my new fragment will go?Thanks
EDIT: I am developing this on a tablet and not a phone.This has now been solved and the above code will add three fragments programmatically.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<FrameLayout
android:id="#+id/list"
android:name="com.david.twofragexample.FragmentOne"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2" />
<FrameLayout
android:id="#+id/viewer"
android:name="com.david.twofragexample.FragmentTwo"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2" />
</LinearLayout>
In your Activity:
FragmentOne one = new FragmentOne();
FragmentTwo two = new FragmentTwo();
fm = getSupportFragmentManager();
fm.beginTransaction().replace(R.id.list, one, "fragmentone").commit();
fm.beginTransaction().replace(R.id.viewer, two, "fragmenttwo").commit();
I suggest you study this:
http://developer.android.com/reference/android/app/Fragment.html
and fully understand the fragment lifecycle, etc. The way I show is quick and dirty, but not neccesarilly best.
As I don't have higher enough reps to comment yet, I will just leave the information here -- the way Rafael T suggested does work nicely, although I also had my doubt at the first place.
1) Define your xml like this:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
2) Add each fragment into the same slot:
View box = v.findViewById(R.id.container);
FragmentTransaction ft = getFragmentManager().beginTransaction();
for (String catalog : mCatalogs) {
Fragment fragment = HighlightedProductFragment.newInstance(catalog);
ft.add(R.id.container, fragment, catalog);
}
ft.commit();
Thanks for the solution for this tricky requirement.
Try it like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
as your activity_main.xml
You asked yourself the right question: where is the id fragment_container, and the answer was: nowhere. >ou also set your layout to horizontal, which makes it very likely, that added Views will be kind of 'out of screen'
I haven't been able to find a way how to dynamically add fragment into existing dynamically added fragment. Do you know, if it is possible?
I am generating fragments this way:
FragmentManager fragMgr = getSupportFragmentManager();
FragmentTransaction xact = fragMgr.beginTransaction();
if(null == fragMgr.findFragmentByTag(FRAG1_TAG)) {
xact.add(10101010, new DateTime(), FRAG1_TAG);
}
if(null == fragMgr.findFragmentByTag(FRAG4_TAG)) {
xact.add(7777, new loginForm(), FRAG4_TAG);
}
xact.commit();
How to add into FRAG4_TAG fragment another one?
Edit2:
I hard coded it's id to be able to work with it in future (where ll is my linearLayout in XML):
FrameLayout frml4 = (FrameLayout)inflater.inflate(R.layout.frame,null);
frml4.setId(7777);
frml4.setBackgroundColor(Color.YELLOW);
ll.addView(frml4);
I assume the problem that you are running into is that there is not an inflated view to add the fragment to because the original fragment, FRAG4_TAG, has not been inflated before you are trying to add it.
You can pass enough information to FRAG4_TAG in the Arguments to let it know that it should create and add a fragment (or what all fragments you need it to have) to itself during it's onCreateView, after the view has been inflated...
The layout for the activity...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="MyActivity"/>
<LinearLayout
android:orientation="vertical"
android:id="#+id/main_frag_container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
The Activity...
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment fragOne = new MyFragment();
Bundle arguments = new Bundle();
arguments.putBoolean("shouldYouCreateAChildFragment", true);
fragOne.setArguments(arguments);
ft.add(R.id.main_frag_container, fragOne);
ft.commit();
}
}
The layout for the fragment...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="20dp">
<TextView
android:id="#+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Some fragment"/>
<LinearLayout
android:orientation="vertical"
android:id="#+id/frag_container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
The fragment...
public class MyFragment extends Fragment {
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.frag_layout, container, false);
boolean shouldCreateChild = getArguments().getBoolean("shouldYouCreateAChildFragment");
if (shouldCreateChild) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
fm.beginTransaction();
Fragment fragTwo = new MyFragment();
Bundle arguments = new Bundle();
arguments.putBoolean("shouldYouCreateAChildFragment", false);
fragTwo.setArguments(arguments);
ft.add(R.id.frag_container, fragTwo);
ft.commit();
}
return layout;
}
}
This example covers the case where you need to dynamically add fragments to a fragment that HAS NOT already been inflated and added to the hierarchy. Adding a fragment to a fragment that HAS already been inflated and added to the hierarchy is as simple as just specifying the target fragments container that you want to add to by ID like you would normally.
As the documentation states "A fragment must always be embedded in an activity".
So when you add a "sub-fragment" it will always belong to the activity even if you add it within your fragment class. For example if you later decide to remove the containing fragment the sub fragments won't be automatically removed.
When I had to do the same I had to store in a vector the sub fragments and manually remove them in the onDestroy methods of my container fragment.
I think that fragments are not thought to be used like this
You cannot insert Fragments into other Fragments. (At least, not yet)
You can however replace Fragments with other Fragments with FragmentTransaction.replace(containerViewId, Fragment).
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.linear1, new activity()).commit();
}
Ok, whenever I try to replace a fragment in my application, it only adds the fragment inside of the container the other fragment is, and leaves the current fragment. I've tried calling replace and referencing the view the contains the fragment, and by referencing the fragment itself. Neither of these work. I can add a fragment to a view with the fragment transaction manager, but even if I try to remove it after its been added, it doesn't work. Any help would be appreciated. Here are my files.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Setup the actionabar. Use setDrawableBackground to set a background image for the actionbar.
final ActionBar actionbar = getActionBar();
actionbar.setDisplayShowTitleEnabled(false);
actionbar.setDisplayUseLogoEnabled(true);
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionbar.addTab(actionbar.newTab().setText(R.string.home_tab_text).setTabListener(this),true);
actionbar.addTab(actionbar.newTab().setText(R.string.insert_tab_text).setTabListener(this));
Fragment fragment = new insert_button_frag();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.button_fragment, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
Here is the layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:id="#+id/button_fragment_container"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<fragment
android:name="com.bv.silveredittab.home_button_frag"
android:id="#+id/button_fragment"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<fragment
android:name="com.bv.silveredittab.quick_insert_frag"
android:id="#+id/quick_insert_frag"
android:layout_width="350dip"
android:layout_height="fill_parent" />
<fragment
android:name="com.bv.silveredittab.editor_frag"
android:id="#+id/editor_frag"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
</LinearLayout>
And here is the fragment code
public class insert_button_frag extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
return inflater.inflate(R.layout.insert_buttons,container, false);
}
}
Like I have said. I have tried referencing the fragments parent view to replace it, and the fragment itself (by id) and still, it only adds the new fragment, inside the containing view the original fragment is in.
I solved this by using a placeholder in my Layout and then attaching my Fragment to it at runtime.
Like you, if I instantiated my Fragment within my xml layout then the contents would remain visible after replacing it with another Fragment at runtime.
The problem is this line:
transaction.replace(R.id.button_fragment, fragment);
replace has two overloaded forms. In both of them, the first argument is the container of the Fragment to be replaced, not the Fragment itself. So, in your case, you need to call
transaction.replace(R.id.button_fragment_container, fragment);
edit: I see in your question that you have tried both. I have tested and verified the behavior. This appears to be a bug in the FragmentTransaction API.
Edit2: not a bug after all. You simply cannot replace fragments added statically in a layout file. You can only replace those you have added programmatically ( Android: can't replace one fragment with another )
I had the same issue. Take a look at this link: Android Fragment Duplication
I wonder if the fact that you're passing the container into the inflater.inflate() method causes it to create the new fragment inside of the old one instead of a wholesale replace. I've been providing 'null' to my inflaters in the working version.
Here's the essentials from the version I have working...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View newFrag = new View(getActivity().getApplicationContext());
newFrag = inflater.inflate(R.id.frag, null);
return newFrag;
}
The google developer guide is quite confusing because it shows first to implement hard coded fragment in you xml. But if you really want to replace existing fragment with the new one, then you should add it(the first) at runtime.
What official site state is
FragmentTransaction replace (int containerViewId, Fragment fragment, String tag)
Replace an existing fragment that was added to a container. This is
essentially the same as calling remove(Fragment) for all currently
added fragments that were added with the same containerViewId and then
add(int, Fragment, String) with the same arguments given here.
You should noticed that it says that Replace an existing fragment that was added to container
So, your xml should look like
someActivity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
...
tools:context="someActivity">
<ImageView
.../>
<LinearLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="bottom"/>
</RelativeLayout>
And than in your activity do in OnCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
[...]
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, new FirstFragment).commit();
}
Than you may easily replace fragment with your animations and event add it to back stack in order to save its state.
private SecondFrag getSecondFrag(){
if(secondFrag == null)
secondFrag = new SecondFrag()
return secondFrag;
}
private void openRechargeFragment(){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.show_frag, R.anim.hide_frag,
R.anim.show_frag, R.anim.hide_frag);
ft.replace(R.id.fragment_container, getSecondFrag(), "myTAG");
ft.addToBackStack(null);
ft.commit();
}