I simply want to replace a fragment from the current fragment and add a new one.
I have studied that Replace is Equal to removeCurrent + Add anotherFragment
But in my situation i am facing a Problem. For the first two times it is running properly but after third attempt instead of replacing . it ads the fragment on me.
My approach fails now. Now i am asking that how can i send an id to other fragment like we do in Activities. I have a listView with a ReadMore button. I simply want to show the details in another fragment and want to send the index of a List.
I listen about some Interface but don't know how to implement . or there an easy way for communication. I tried doing it by passing it in Constructor . but it will give me an error . because
how to get currentFragment and hide it?
how to add onBackPressed to fragment.
how to send data between fragments The easy way.
i know how to hide or show a fragment
getFragmentManager().beginTransaction().hide(frag[j]).commit();
getFragmentManager().beginTransaction().show(frag[0]).commit();
also know how to add or replace a fragment
getFragmentManager().beginTransaction().add(R.id.container, frag[i])
//.addToBackStack(null)
.commit();
getFragmentManager().beginTransaction().replace(R.id.container, frag[i])
//.addToBackStack(null)
.commit();
Tell me a better approach to send data and why my layout add instead of replacing.
I recommend using EventBus for Activity/Fragment/Service or any other communication.
There is a good one from Square: http://square.github.io/otto/
Or this one (also very good): https://github.com/greenrobot/EventBus
It makes it simplier and your code gets cleaner.
It is pretty easy to send data to fragment with constructor.
In your fragment class, add constructor like this:
public class MyFragment extends Fragment{
String id;
public MyFragment(String id)
this.id = id;
}
Then, when calling a fragment,you can easily send data like this :
getSupportFragmentManager().beginTransaction().replace(android.r.id.container,new MyFragment("123")).commit();
You can't override onBackPressed within fragment, you can only do that in activity
You can set try set the variables in the fragment as public static then you can declare them before you instantiate your fragment to be shown.
in your onDestroy method of the fragment you can set the variables = null, so they dont take space in memory.
could be smth like this
MyFragment.theString = "A String";
getSupportFragmentManager().beginTransaction().replace(android.r.id.container,new MyFragment()).commit();
And in your fragment
public static String theString;
...
public void onDestroy(){
super.onDestroy();
theString = null;
}
Related
Ok, so I've a Fragment inside which I use getActivity().getClass().getSimpleName() to get the name of the activity that contains it.
Now, I've a method called sampleMethod() inside that activity, and to call it from the fragment I use ((MyActivity) getActivity()).sampleMethod(); This works fine as well.
My question is that how can I use the activity name in the statement ((MyActivity) getActivity()).sampleMethod(); dynamically. Obviously, I do get the name from getActivity().getClass().getSimpleName().
So what I want is something like
`((getActivity().getClass().getSimpleName()) getActivity()).sampleMethod();
Syntactically, the above is incorrect. What's the correct way?
All the Activities that include this fragment should implement an interface, let's say
interface Sample {
public void sampleMethod();
}
then in your fragment
((Sample)getActivity()).sampleMethod();
I have a headless fragment to retain my data during config changes.
rFrag = new RetainedFragment();
getSupportFragmentManager()
.beginTransaction()
.add(rFrag, MODEL)
.commit();
What is the best way to access this fragment while inside of another activity or fragment besides the original activity that the headless fragment is attached to?
Using this doesn't work:
RetainedFragment rFrag = (RetainedFragment)getSupportFragmentManager
.findFragmentByTag(model);
I did a search and I believe this is because I don't have the retained fragment added onto the backstack, but adding a headless fragment onto the backstack isn't what I want to do.
Right now I just set the retained fragment to be public and static like this:
public static RetainedFragment rFrag;
But I feel like this isn't good practice to use static variables like that.
First of all, I don't know what you mean by "headless fragment".
Secondly, I don't know what RetainedFragment() class is but I will assume that it is just a class you created that extends Fragment.
Thirdly, you can't access a Fragment through other Activity. Every fragment is attached to one Activity and when that Activity is not visible its Fragments are not accessible.
Lastly, even if you force to access by using static methods and fields and such, you are right, it is not a good practice. You can, and should, use Intent extras and Fragment arguments to pass data from one to another. You mentioned you need to retain some data, so you actually don't really need the whole Fragment, right? You can just save, load and pass around the data you need.
is there a way to send some data from an activity to a running fragment?
In my app I'm adding a second fragment over another fragment. I intentionally use the add method instead of the replace method. So now I want to hide my second fragment with
fragmentManager.popBackStack();
and my first fragment reappears. After hiding the second fragment I want to send some data from my activity to the still running frist fragment.
Any idea how to do this? It doesn't work with bundles (put extra), because I don't rebuild the fragment, I just hide the second one!
one simple solution is:
MyFragment oldFragment = (MyFragment) fragmentManager.findFragmentById(R.id.fragment_place);
fragmentManager.popBackStackImmediate();
MyFragment newFragment = (MyFragment)fragmentManager.findFragmentById(R.id.fragment_place);
newFragment.postData(...);
You can use an EventBus library like this one, it's easy to use and very convenient.
You can use tags on the Fragments when you create them to call them when needed.
getFragmentManager().beginTransaction()
.add(R.id.content, new SomeFragment(), SomeFragment.class.getSimpleName())
.commit();
So above I use the simple name of the class to tag the fragment when I create and add it to the activity.
SomeFragment fragment = (SomeFragment) getFragmentManager().findFragmentByTag(SomeFragment.class.getSimpleName());
And I can call it back when I need it and know it is being displayed like above, now I can call send it data like normal by calling a public method in the custom fragment and passing it the data as a param.
I am facing a problem implementing an interface defined in one fragment and using it to another. I know I need to do this through activity but I have added fragments dynamically inside another fragment. Please look at the snapshot to understand more about my problem.
. I have a fragment called ACTIVITY fragment inside which I load fragments dynamically. The Comments textview is clickable and when clicked it a CommentDialogFragment is shown. This dialog fragment is shared by all the fragments. Code when comment clicked:
FragmentTransaction ft = getActivity()
.getSupportFragmentManager().beginTransaction();
CommentDialog fragment = CommentDialog.newInstance(id,
"Activity");
ft.addToBackStack(null);
fragment.show(ft, null);
I want to increment the comment count. For that I made an interface:
public interface IncrementComment {
public void increaseCommentCount(boolean increase);
}
I am unable to use this interface in my fragment inside the ACTIVITY fragment. The interface is detected on the Activity that holds all these fragments. Heres the interface in my MainActivity class I get the data upto this point:
#Override
public void increaseCommentCount(boolean increase) {
// TODO Auto-generated method stub
Log.d("interface main activity", "called");//this is called
}
Now I am unable to pass data from this activity code to my fragment because the fragments are loaded dynamically and there can be any number of fragments(user can see their old post).
So I tried to make a fragment implement the interface to update the value of the textview. But I couldnot get it working as it is never called. Can someone point me in the correct direction. I tried most of the links in SO like this and from other sources like this but none of them fit my requirement.
i have 2 fragments
in 1st fragment i am calling a 2nd fragment on button click which returns data(on click on list items) and again open 1st fragment with the result displayed (i.e some String data of list item).
But the problem is when i comeback from 2nd to 1st again after selection in 2nd fragment my 1st fragment is displayed only but do not react on button click.
this is my first fragment
i have searched lot but i found activity fragment communication only not fragment to fragment
if any body has solution for fragment to fragment only.please help
There are a lot of ways, here some hints.
Generally speaking you can use "listeners" (interfaces)
Official Google Docs
Similar question on StackOverflow
More elegant way using "event bus" paradigm, a clean and simple library is Otto
Another (slightly dirty) way if you are using the compatibility library would be to use the LocalBroadcastManager. Your fragments can send (and listen for) local broadcasts to notify each other of events...
Try like this (Example an integer array):
//Create a public class:
public class Values{
public static int[] val = null;
}
//Set array in one fragment:
Values.val = int[] arr1;//arr1 containing your values
//Get array in another fragment:
int[] arr2 = Values.val;