I am having and issue about closing a Fragment.
The reason why I cannot close the Fragment, within the customized Fragment itself, with the following chaining
getActivity().getFragmentManager().beginTransaction().remove(this);
seem to be inheritance, since my customized Fragment inherits from ..
extends android.support.v4.app.Fragment
Android Studio is complaining about the argument in remove(), - "this"
remove (android.app.Fragment) in FragmentTransaction cannot be applied to se.fragmenttest.app.myfrafmentest180406.MyFragment)
The strange this is that the same call seem to work from within MainActivity where the Fragment is instanciated.
the whole class
public class MyFragment extends android.support.v4.app.Fragment {
private View fragmentView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup containter, Bundle savedInstanceState) {
fragmentView = inflater.inflate(R.layout.fragment_layout, containter, false);
Button button = (Button) fragmentView.findViewById(R.id.okbutton_id);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
closeFragment();
}
}
);
return fragmentView;
}
private void closeFragment() {
getActivity().getFragmentManager().beginTransaction().remove(this);
}
}
EDIT:
code for MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyFragment myFragment = new MyFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.container, myFragment, "myfragment");
fragmentTransaction.commit();
fragmentTransaction.remove(myFragment);
}
I tried to remove the fragment in the MainActiviy and there it WORKS. And more - I can put the reference in remove() which I cannot in the Fragment class
Use this
getActivity().getFragmentManager().popBackStack();
(or) use can specify tags
Example reference
You can pop the fragment by name. While adding fragments to the back stack, just give them a name.
fragmentTransaction.addToBackStack("fragB");
fragmentTransaction.addToBackStack("fragC");
Then in Fragment_C, pop the back stack using the name ie.. fragB and include POP_BACK_STACK_INCLUSIVE
someButtonInC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = getActivity()
.getSupportFragmentManager();
fm.popBackStack ("fragB", FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
});
I'm not at my main computer right now, so can't check...
But i think you need to call getSupportFragmentManager() rather than getFragmentManager().
EDIT
Now I'm back at my computer I can confirm it is what I said above. It also helps that you have posted your activity code.
In your MainActivity you call:
MyFragment myFragment = new MyFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
i.e. you call getSupportFragmentManager() which is correct, and why it works.
..but in your Fragment you call the standard getFragmentManager() as below:
getActivity().getFragmentManager().beginTransaction().remove(this);
and as the fragment extends a Support fragment, when you try and call this it can't be found. However, if you change the above line to this:
getActivity().getSupportFragmentManager().beginTransaction().remove(this);
this will no longer not be found and your code should run.
Related
I have simple activity and fragment transaction. What i noticed that on configuration changes oncreateView of Fragment is called twice. Why is this happening?
Activity Code Here :
#Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println("Activity created");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager manager = getSupportFragmentManager();
BlankFragment fragment = new BlankFragment();
addFragmentToActivity(manager,
fragment,
R.id.root_activity_create
);
}
public static void addFragmentToActivity (FragmentManager fragmentManager,
Fragment fragment,
int frameId)
{
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(frameId, fragment);
transaction.commit();
}
Fragment Code Here :
public class BlankFragment extends Fragment {
public BlankFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank, container, false);
}
}
On first load onCreateView() is called once
But onRotation onCreateView() is called twice
why ?
Because of this transaction.replace(frameId, fragment); Really? Yes,I mean because of fragment .You already have one fragment onFirst load, When you rotate onCreate() will be called once again, so now fragment manager has old fragment ,so it methods will execute(once),and next you are doing transaction replace() which will remove old fragment and replace it with new once and again(onCreateView() will be called for second time). This is repeating for every rotation.
If you use transaction.add(frameId, fragment,UNIQUE_TAG_FOR_EVERY_TRANSACTION) you would know the reason. for every rotatation, no.of onCreateView() calls will increase by 1. that means you are adding fragments while not removing old ones.
But solution is to use old fragments.
in onCreate()of activity
val fragment = fragmentmanager.findFrgmentByTag("tag")
val newFragment : BlankFragment
if(fragment==null){
newFragment = BlankFragment()
}else{
newFragment = fragment as BlankFragment()
}
//use newFragment
Hope this solves confusion
Android automatically restores the state of its views after rotation. You don't have to call addFragmentToActivity again after rotation. The fragment will automatically be restored for you!
In your case, it happens twice because:
1. Android restores the fragment, its onCreateView is called
2. You replace the restored fragment with your own fragment, the oncreateview from that fragment is called too
do this:
if (savedInstanceState == null)
{
addFragmentToActivity(manager, fragment, R.id.test);
}
I'm new Android programming. Earlier I was working with activities, where i could implement onClick on an ImageButton and go to a different activity.
Now I need to do the same but using Fragments. I have a prototype with a menu that always appear on screen and can show different activities to the user. The different lactivities would be inside this container.
Now I want to place an ImageButton inside a fragment and make that the screen shows the next fragment. But I'm confused how to do it.
I have the following components:
Activity_main(java)+activity_main.xml (with menu)
Fragment1(java)+fragment1.xml(working normal)
Inside this layout I have an ImageButton and want to show Fragment2
Fragment2(java)+fragment2.xml
How should look Fragment1 to can call Fragment2?
I will be glad if the answer could be the clearest possible because I'm new on it, and maybe I could forgot an obvious step. Thanks
Simply make a method in your activity which will always change/replace fragment when you invoke it. something like
public void updateFragment(Fragment fragment){
//add fragment replacing code here
}
in your fragment, invoke it some thing like this
((YourActivity)getActivity()).updateFragment(new YourFragment());
since, it is just an idea which works fine but still you can improve the logic.
Actually, going from one fragment to another is almost similar to going from one activity to another. There are just a few extra lines of code.
First, add a new Java class named SingleFragmentActivity which would contain the following code-
public abstract class SingleFragmentActivity extends AppCompatActivity
{
protected abstract Fragment createFragment();
#LayoutRes
protected int getLayoutResId()
{
return R.layout.activity_fragment;
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(getLayoutResId());
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null)
{
fragment = createFragment();
fm.beginTransaction().add(R.id.fragment_container, fragment).commit();
}
}
}
Make your activities in the following format-
public class SomeActivity extends SingleFragmentActivity
{
#Override
protected Fragment createFragment()
{
return SomeFragment.newInstance();
}
}
And your fragments like this-
public class SomeFragment extends Fragment
{
public static SomeFragment newInstance()
{
return new SomeFragment();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_some, container, false);
return v;
}
}
After this everything has the same code as you have for activities except for one small detail which is your onCreateView(LayoutInflater, ViewGroup, Bundle) class. This is how you would write it-
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_some, container, false);
mTextView = (TextView)v.findViewById(R.id.some_text);
mButton = (Button)v.findViewById(R.id.some_button);
mTextView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
check();
}
});
return v;
}
And that is it!
Hi i hope you are already aware about the fragments and their uses but still here is a brief. They are child to an activity and an activity can have more than one fragment so you can update your layout without changing activity just by changing fragments.
You can found more on fragment here : https://developer.android.com/training/basics/fragments/index.html
Back to the original problem, supposed you are in MainActivity.java and you want to load fragment in it, so you do this to load fragment first time.
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame, new Fragment1);
transaction.addToBackStack(null);
transaction.commit();
You will need this method to change fragment from another fragment, so add this in your MainActivity
public void changeFragment(Fragment fragment){
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame, new Fragment1);
transaction.addToBackStack(null);
transaction.commit();
}
Now from a button click in this fragment
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).changeFragment(new Fragment2);
}
});
Hope it will help!
I have an activity containing multiple fragments. Activity initially have fragment and in it have two buttons. Upon clicking this button I have to replace the fragment by new fragment. Each fragment has various widgets and replace the current fragment as various events.
This is my problem. How can I achieve this?
Suggest me ideas.
you can replace fragment by FragmentTransaction.
Here you go.
Make an interface.
public interface FragmentChangeListener
{
public void replaceFragment(Fragment fragment);
}
implements your Fragment holding activity with this interface.
public class HomeScreen extends FragmentActivity implements
FragmentChangeListener {
#Override
public void replaceFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();;
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(mContainerId, fragment, fragment.toString());
fragmentTransaction.addToBackStack(fragment.toString());
fragmentTransaction.commit();
}
}
Call this method from Fragments like this.
//In your fragment.
public void showOtherFragment()
{
Fragment fr=new NewDisplayingFragment();
FragmentChangeListener fc=(FragmentChangeListener)getActivity();
fc.replaceFragment(fr);
}
Hope this will work!
NOTE: mContainerId is id of the view who is holding the fragments inside.
You should override Fragment's onString() method as well.
Well even I am learning android...
I solved same problem recently, "How to Change Fragment On button's click event".
buttonName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction fragmentTransaction = getActivity()
.getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame1, new Homefragment());
fragmentTransaction.commit();
}
});
Here frame1 is id of FrameLayout which have define in my DrawerLayer's XML.
So now whenever I want fragment transaction I use this code. Each time it will replace frame1 instated of your last fragment.
FragmentTransaction fragmentTransaction = getActivity()
.getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame1, new newfragment());
fragmentTransaction.commit()
Hope this will help..
You can use the following to replace a fragment on button click of that fragment:
getFragmentManager().beginTransaction().replace(R.id.main_content, new insertFragmentNameHere()).addToBackStack(null).commit();
Define an interface and call it IChangeListener (or something like that) and define a method inside which will do the work (ex, changeFragment()) (or call another method which will do the work) for changing the fragment).
Make your activity implement the interface, or make an anonymous class within the activity implement it.
Make a paramerized constructor of your fragment, which accepts a IChangeListener parameter.
When initializing the fragment, pass your IChangeListener implementation (the anonymous class or the activity, implementing it)
Make the onClick listener of the button call the changing method of the IChangeListener.
From the future 2017 and after, there exists different libraries that triggers Events using Bus and now you can use it to tell the activity when an event is trigger in a fragment that it owns.
Refer to:
RxBus with RxJava
You can check new architectures suggested by Google
ViewModel
Don't use the approach in the accepted answer, get really ugly with more than 3 different events from fragments
you can try this code it's work fine with me , inflate the layout to view , Define the buton and on click ,
Button btn_unstable;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home,container,false);
btn_unstable = (Button)view.findViewById(R.id.btn_unstable);
btn_unstable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_replace, new UnstableFragment()).commit();
}
});
return view;
}
And first of all thank you anyway for your help.
This is a difficult question for me.
Please I have an activity that contains 5 Fragments; on user interaction the Fragments get swapped.
I am using the ACL.
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
stackArray =new ArrayList<Integer>();
favQ =new ArrayList<Stock>();
tablet=true;
mBound = false;
fragmentActivity = this;
setContentView(R.layout.splashmain);
splashfragment =new splashFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.splashview,splashfragment);
fragmentTransaction.commit();
/*
other stuff....
*/
fragmentlista = new listafragment();
fragmentfavourites= new favouritesFragment() ;
worstbest = new WorstBest();
searchfragment = new searchFragment();
/*
other stuff....
*/
lt = mService.ritira();
worst=mService.ritiraWorst();
best=mService.ritiraBest();
favQ.clear();
favQ.addAll(mService.ritiraFav());
fragmentlista.prendiLista(lt);
worstbest.prendiListaWorst(worst);
worstbest.prendiListaBest(best);
if(favQ.size()>0)fragmentfavourites.prendiLista(favQ);
// --->>>>HERE THE SAME METHOD enableAll() WORKS!!! <---
// --->>>>HERE THE SAME METHOD enableAll() WORKS!!! <---
splashfragment.enableAll();
// --->>>>HERE THE SAME METHOD enableAll() WORKS!!! <---
// --->>>>HERE THE SAME METHOD enableAll() WORKS!!! <---
/*
other stuff....
*/
}
//Method invoked to setup the configuration of the screen is layoutSchermo(int conf)
public static void layoutSchermo(int conf){
//Check if it is a Tablet in Landscape mode or not
//if it finds v2 than we are on a LARGE screen, then we check ORIENTATIO
fragmentActivity.setContentView(R.layout.main);
View v2 =(View)fragmentActivity.findViewById(R.id.view2);
if(v2==null
&
fragmentActivity.getResources().getConfiguration().orientation==
Configuration.ORIENTATION_PORTRAIT)
tablet=false;
//Calls the screen configuration LIST
if(conf==LIST){
fragmentActivity.setContentView(R.layout.main);
FragmentManager fragmentManager = fragmentActivity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(splashfragment);
fragmentTransaction.commit();
fragmentManager.executePendingTransactions();
//Remove old Fragment splashfragment
//At this point I expect the fragment splashfragment is destroyed
//OR NOT???
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);
if(!tablet){fragmentTransaction.replace(R.id.view1, fragmentlista);}
if(tablet){
fragmentTransaction.replace(R.id.view1, splashfragment);
fragmentTransaction.replace(R.id.view2,fragmentlista );
} fragmentTransaction.addToBackStack(null);
stack= fragmentTransaction.commit();
stackArray.add(stack);
//Brand new fragments added
// --->>>>HERE THE SAME METHOD enableAll() NOT WORKING!!! <---
// --->>>>HERE THE SAME METHOD enableAll() NOT WORKING!!! <---
splashfragment.enableAll();
}
------------
So basically what happens and where the problem is:
The problem is in the method
layoutSchermo(int conf)
In the method layoutSchermo(int conf),
I detach a Fragment (splashfragment) and reattach it (together with another one).
It is not clear to me if when I call
remove(splashfragment)
Actually the Fragment is destroyed or not?
Additionally, whenever the Fragment freshly added is a new one or the old one,
why the call to
splashfragment.enableAll();
Has no effect ?
I expect it to work either it is the new or old Fragment!
Please enlighten me!
Thanks
maurizio
----------
EDIT EDIT EDIT EDIT EDIT EDIT
Here is the code of the fragment (I do not think it helps much)
ublic class splashFragment extends Fragment {
public View v;
public Button buttonfav;
public Button buttonBW;
public Button buttonSe;
public Button buttonLi;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v=inflater.inflate(R.layout.splashnew, container, false);
RelativeLayout box1 = (RelativeLayout)v.findViewById(R.id.box1);
//box1.setBackgroundColor(Color.BLUE);
buttonfav=(Button)v.findViewById(R.id.heart);
buttonBW=(Button)v.findViewById(R.id.star);
buttonSe=(Button)v.findViewById(R.id.search);
buttonLi=(Button)v.findViewById(R.id.lista);
buttonfav.setBackgroundResource(R.drawable.hearth_gray_tansp);
buttonBW.setBackgroundResource(R.drawable.star_gray_trans);
buttonSe.setBackgroundResource(R.drawable.search_gray_transp);
buttonLi.setBackgroundResource(R.drawable.list_gray_trans);
buttonfav.setEnabled(false);
buttonBW.setEnabled(false);
buttonSe.setEnabled(false);
buttonLi.setEnabled(false);
buttonfav.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Quotes.layoutSchermo(Quotes.FAVOURITES);
}});
buttonBW.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Quotes.layoutSchermo(Quotes.BESTWORST);
}});
buttonSe.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Quotes.layoutSchermo(Quotes.SEARCH);
}});
buttonLi.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Quotes.layoutSchermo(Quotes.LIST);
}});
return v;
}
#Override
public void onSaveInstanceState(Bundle outState) { }
public void enableAll(){
buttonfav.setEnabled(true);
buttonfav.setBackgroundResource(R.drawable.hearth);
buttonBW.setEnabled(true);
buttonBW.setBackgroundResource(R.drawable.star);
buttonLi.setEnabled(true);
buttonLi.setBackgroundResource(R.drawable.list);
buttonSe.setEnabled(true);
buttonSe.setBackgroundResource(R.drawable.search);
}
}
When exactly fragments are destroyed can't be known with any certainty. All you know is that it's called after onStop() and before onDetach().
As for your splashFragment.enableAll(), you haven't showed us what that method is so how can we know why it isn't working... Also, you haven't showed us the more general context of this layoutSchermo method. I say this because I suspect you're doing this all wrong. You have a static method, referencing activities somehow...(not clear how that's happening), setting the contentview on that activity reference..the whole thing just sets off some red flags.
SplashFragment.enableAll is most likely something that needs to be called inside of that Fragment's onAttach or onResume, but again it's impossible to know without some explanation from you.
EDIT
Ok, so I think you're going about this incorrectly. What you are effectively trying to accomplish is to "configure" your Fragment in a certain way (depending on some state) when you display it again. The issue here is that you don't know exactly when the View hierarchy of a Fragment is inflated or when exactly it's attached to the Activity, etc. In other words, trying to call methods that affect the UI of your fragment simply on the basis of having a reference to the object of a Fragment is a mistake. You need to hook into the lifecycle of your Fragment and do things "the correct way."
Here's what I recommend: create a static constructor for your Fragment that makes it easy to create the properly configured Fragment that you want. Here's what that might look like:
public class SplashFragment extends Fragment {
public static SplashFragment newInstance(Bundle bundle) {
SplashFragment splashFragment = new SplashFragment()
splashFragment.setArguments(bundle);
return splashFragment;
}
// or alternatively
public static SplashFragment newInstance(int favResource, int bwResource, int liResource, int seResource,
boolean favEnabled, boolean bwEnabled, boolean liEnabled, boolean seEnabled) {
SplashFragment splashFragment = new SplashFragment()
Bundle bundle = new Bundle();
bundle.putInt("fav_res", favResource);
bundle.putInt("bw_res", bwResource);
bundle.putInt"li_res", liResource);
bundle.putInt("se_res", seResource);
bundle.putBoolean("fav_enabled", favEnabled);
//...And so on
splashFragment.setArguments(bundle);
return splashFragment;
}
//Then....
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//setup your view as normal...then
buttonFav.setBackgroundResource(getArguments().getInt("fave_res"));
//.....etc
}
}
Now if you really need to be able to manipulate a Fragment without creating a new instance, then the only way I can think to do this is to add the fragment with a tag, as in the
replace(int containerViewId, Fragment fragment, String tag)
and
add (Fragment fragment, String tag)
varieties.
Then, later you can try to ask the fragment manager to find those fragment for you, i.e.
SplashFragment splashFragment = (SplashFragment) getFragmentManager().findFragmentByTag("some tag here");
Check that it's not null and then call your method on it...
I've been trying to get ActionBarSherlock working with Google's fragment tutorial and run into a problem when trying to add the "content" fragment to the view. This line produces the following exception
getFragmentManager().beginTransaction().add(android.R.id.content, content).commit();
The method add(int, Fragment) in the type FragmentTransaction
is not applicable for the arguments (int, ContentFragment)
The code is identical to Google's (http://developer.android.com/guide/components/fragments.html) except I've extended to SherlockActivity where needed. ContentFragment/Activity is merely what I've called Details activity.
Even if I take out all of the ABS references to make it a normal example, I get the same problem. I have a feeling its to do with the android support library, but I cant for the life of me figure it out.
Use getSupportFragmentManager() instead of getFragmentManager().
How does your fragment class look like? This code works fine for me:
android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
FragmentADetail frag = new FragmentADetail();
ft.replace(android.R.id.content, frag);
ft.addToBackStack(null);
ft.commit();
And my FragmentADetail class looks like this:
public class FragmentADetail extends SherlockFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getSherlockActivity().getSupportActionBar().setDisplayHomeAsUpEnabled(true);
View v = inflater.inflate(R.layout.fragment_a_detail_layout, container, false);
v.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//left empty on purpose to capture the onClick event.
}
});
return v;
}
#Override
public void onStop()
{
super.onStop();
getSherlockActivity().getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
}