A fragment and 2 activity that use the fragment - android

I am new at developing Android App.I am try to use a dynamic fragment which is used 2 activity like (show detail activity and edit details activity).How can I understand the fragment is used by which activity in onActivityCreated() method on MyFragment class. How can I handle this issue please help me thanks in advance

Try this in your Fragment onActivityCreated() method
FragmentActivity activity = getActivity();
if(activity instanceof show detail activity){
// Your ShowDetailsActivity
}else if(activity instanceof edit details activity){
// Your EditDetailsActivity
}

Jagadesh's solution will work, but fragments should operate independent of the activity.
You might want to consider adding a static method like "getInstance" that will accept parameters and return an appropriate instance of the fragment if some functionality shoudl be custom for the calling activity.
If you want to call the activity back, then you might think about having the activities register a callback or listener that the fragment can invoke.

Related

Activity to RecyclerView Adapter Communication(Recyclerview in Fragment)

I have a Activity which contains a fragment with recyclerview.
The recyclerview has few editable fields and need to put validations on clicking a button on activity.
Please let me know the solution or any techniques to overcome this problem statement
use this (click here ) functionality for data sharing between Fragment to fragment , Fragment to Activity and Activity to Activity
1) in your onCreate declare the BUSand register it
Bus bus = new Bus();
bus.register(this);
2) send data or any action using
bus.post(<your data or any Item>);
3) don't forgot to unregister in your onestroy
bus.unregister(this)
You can get that fragment instance either by 'ID' or by tag (you would need to give a tag while adding this fragment).
Now you can call any public method of that fragment using its instance.
For Example (Using tag), if you want to call a public method 'show()' of FragmentA. Then while adding it to the activity give it a tag like this:
Fragment fragmentA = new FragmentA();
getFragmentManager().beginTransaction()
.add(R.id.fragment_container,fragmentA,"YOUR_TARGET_FRAGMENT_TAG").commit();
And to get its instance (on a button click or as required):
FragmentA fragmentA = getFragmentManager().findFragmentByTag("YOUR_TARGET_FRAGMENT_TAG");
fragmentA.show();
Declare in your fragment the RecyclerView as public
Declare in your activity the fragment as variable
in your activity on click listener get the recyclerview with
fragment.recyclerview

How to make DialogFragment call a method inside another Fragment

I have a tabbed activity that shows a fragment by a viewpager, as usual.
This fragment have a list.
One of the actions of the user shows a dialogfragment to user insert a new item in this list.
I show the dialogfragment with edittexts to user create a new item.
The question is: how can I insert this item on the viewpagers' fragment list?
From any fragment I can call getActivity() to access the activity, but how access another fragment that is being shown behind the dialogfragment?
Thanks in advance.
Fragment with the List items - FragmentA
Dialog - NewItemDialogFragment
The method you're missing is setTargetFragment(). While building your NewItemDialogFragment, invoke this method passing the FragmentA as the target fragment for your dialog.
Later, you can access the FragmentA instance by calling getTargetFragment() inside NewItemDialogFragment and cast it to the FragmentA and add newly created item.
Alternatively, you can create the contract interface between the FragmentA and the NewItemDialogFragment
It sounds like you want to get the results from the dialogfragment (what the user has inserted on the dialogfragment edit-texts) and use this in the fragment that called the dialogfragment (to add as new item to the list) - in that case, the selected answer here solves this problem - also I think this Gist is a good resource to reference.
In your case, I also think implementing some sort of a custom listener/callback as they did in this Gist is a good idea. Hope this helps.
You can use event bus for this.
http://square.github.io/otto/
This is an example of usage:
Bus bus = new Bus();
bus.post(new AnswerAvailableEvent(42));
#Subscribe public void answerAvailable(AnswerAvailableEvent event) {
// TODO: React to the event somehow!
}
bus.register(this); // In order to receive events, a class instance needs to register with the bus.

What is meant by "Activity this fragment is currently associated with"?

Here in the doc I see that when I call getActivity() from my fragment class, I get the activity object that the fragment is currently associated with.
Suppose if fragment is associated with MainActivity then getActivity() doesn't give an object of the MainActivity class.
I'm unable to understand the difference between Activity activity; and Activity activity = getActivity();
Can anyone please explain me what this "Return the Activity this fragment is currently associated with" actually mean ?
Sorry for asking simple question.
Thanks.
Edit :
Went through this also, got a better understanding.
Association is simple.
Like in real life.
You are a student (Fragment).
You are getting knowledge in Chicago university (MainActivity).
As you are student you will be associated(attached) to university.
And if someone ask you :
-What is your university?(call getActivity() from Fragment)
You will answer :
-I from Chicago university(return object which refered to MainActivity)
If you change the university - you will respond differently.
That's all :)
The simplest answer would be:
"Return the Activity this fragment is currently associated with"
is activity to which this fragment was added.
Then to make things clear.
Activity activity;
This creates reference to activity object, and at start this one is empty (equal to null), until you write some activity object to it.
Activity activity = getActivity();
Here we do 2 things, firstly we create reference to activity object and then we write to this object value of function getActivity(), that if called from fragment will return associated activity.
And lastly why this is not MainActivity? Well it actually may or may not be. :)
And to check if this is actually MainActivity try this :)
Activity activity = getActivity(); // let get our activity
if (activity == null) {
/* this mean we are not attached to activity, possibly, fragment was not shown yet */
}
if (activity instanceof MainActivity) { // we check if activity is actually Main activity.
MainActivity mainActivity = (MainActivity) activity; // and if it is we can do something with it after we cast it.
}
Then at the end i will add one link that might also help: fragment

Fragment without activity

I have been asked an interview question: Can a fragment exist without activity? I searched for answers but didn't get a proper answer and explanation. Can someone help?
Yes, you can do this anywhere:
new YourFragment();
As fragments must have a parameter-less constructor.
However its lifecycle doesn't kick in until it is attached. So onAttach, onCreate, onCreateView, etc. are only called when it is attached. So most fragments do nothing until they are attached.
It can exist as an object in memory (by creating it with new), but it needs to be attached to an Activity in order to appear on the screen, assuming it has any UI (fragments don't have to have UI).
A Fragment can exist independently, but in order to display it, you need the help of an Activity. The Activity will act like a container for the Fragment(s).
A fragment is not required to be a part of the Activity layout; you may also use a fragment without its own UI as an invisible worker for the Activity but it needs to be attached to an Activity in order to appear on the screen.
As soon as you create an instance of the Fragment class, it exists, but in order for it to appear on the UI, you must attach that fragment to an activity because a fragment's lifecycle runs parallel to an activity's lifecycle. Without any call to Activity's onCreate(), there will be no call for onAttach(), onCreate(), onCreateView() and onActivityCreated() of fragment and so it can't be started.
I read above top rated answer , i am not disagreeing but android already provides to make independent fragment without activity DialogFragment , which extends fragment . if you want show in full screen first extends DialogFragment then
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_FRAME, android.R.style.Theme_Holo_Light);
}
Android app must have an Activity or FragmentActivity that handles the fragment.
Fragment can't be initiated without Activity or FragmentActivity.

Communicating between fragments in Android

Based on the example from http://developer.android.com/training/basics/fragments/communicating.html I tried to reproduce the communication between two fragments which are sub fragments of a larger fragment.
In the example, AB activity contains A fragment and B fragment. But I am trying to achieve the same but in my case AB Fragment contains A fragment and B fragment.
The problem is the overridden method in the AB Fragment never gets called. Does this not work because the containing component is a Fragment and not a Activity like in the example? Am I missing out something here?
If you are referring to onClick() or some other onSomething() handler, then these always get called in the Activity class, not the fragment. So in the example you linked, the onArticleSelected() must remain in the Activity, even if you have nested fragments.
To pass info on to the fragment, you have a few options. One, you can keep a reference to the fragment within the activity. This might be lost if your activity recreates (settings event for example).
The second and better way would be to tag your fragments, and then use findFragmentByTag.
When you add your fragment (notice the parameter "my_fragment" which is the tag I gave to the fragment):
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, myFragment, "my_fragment").commit();
Or when you replace one fragment with another:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, myFragment, "my_fragment").comit();
Then, when you want to do something in the fragment from within your onArticleSelected of the activity:
Fragment fragment = getSupportFragmentManger().findFragmentByTag("my_fragment");
if (fragment != null) {
fragment.articleSelected(articleId);
}
You can always use an Interface to communicate between fragments. It is the safest way to do so.

Categories

Resources