Android UI fragments. Changing fragment due to button push - java

I'm trying to open a new fragment based on a button push in a previous fragment. What's the best way to implement this?
I'm curious if it's Activity -> .add + .commit original fragment - > from that fragment.java .replace new fragment?
Or do I need to pass an intent back up to the activity and create/replace that fragment from the activity?
So summarize: Activity A - > Fragment 1 - > Fragment 2.
I'm also slightly confused on what things I [need] to #Override. I think only onCreate and onCreateView [within each fragment]?
I'm only looking for high-level here; I want to struggle through the code myself.

Fragments are generally unaware of their host so I would use the standard callback method to call your activity and ask it to switch fragments.
Create an interface
Have your activity implement the interface.
Cast the getActivity() call to your interface.
Call the interface method.
This is much cleaner than casting the host activity and calling methods on it. It also means your fragment can be hosted in different activities with no cast errors.
http://developer.android.com/training/basics/fragments/communicating.html

You need to cast getActivity like:
((MyActivity) getActivity())
And then if you have that, you can call a method in yout activity:
((MyActivity) getActivity()).replaceFragments(Object... params);
And inside the method you should do the replace fragment process.
So simply you have the right idea.

Related

Access fragment method from intent activity

I have a fragment, and I am starting an activity from the fragment. Now I want to call a method from the fragment in the new activity.
I tried to use interface but it seems I can't since I don't create an object of new activity in the fragment to have it call the setListener(). I am using intent to fire up the new activity.
I am not able to find how I can get fragment instance in new activity or how to call a method in the fragment. Any help would be great!
A fragment is tightly coupled with the Activity. You always need to create the Activity as the host for the fragment.
From the documentation:
A Fragment represents a behavior or a portion of user interface in an
Activity. You can combine multiple fragments in a single activity to
build a multi-pane UI and reuse a fragment in multiple activities. You
can think of a fragment as a modular section of an activity, which has
its own lifecycle, receives its own input events, and which you can
add or remove while the activity is running (sort of like a "sub
activity" that you can reuse in different activities).
So, you need to do the communication between Activities. An activity should not communicate with a fragment it didn't host. But it should communicate with the Activity where the fragment is hosted.
For example,
if you have two Activity which are ActivityOne and ActivityTwo. Where ActivityOne has a Fragment called ActivityOneFragment.
When you need to get the ActivityOneFragment from ActivityTwo, you need to communicate with the ActivityOne then tell it to get the ActivityOneFragment:
ActivityTwo -> ActivityOne -> ActivityOneFragment
You shouldn't do this:
ActivityTwo -> ActivityOneFragment
No, you can do not that. Because the background activity is paused/ dead. so you can not access its method.
if it is general method, you can put that method in other class. call it your utility class.

Activity - Fragment onBackPressed()

I am having some problems to understand the differences between Activity and Fragment.
I have done an activity called "PublicarActivity" and a Fragment called "PublicarFragment".
They have exactly the same code (with some differences to work as a fragment and as an activity) so that is not a problem.
My problem is that I do not really know how to work with "onBackPressed". I know that before than calling the fragment, you should add it to the stack, but right now I would like to do something a little bit more complicated.
This is the code for my Activity's onBackPressed:
#Override
public void onBackPressed() {
if(layout_activado){
verificable.toggle();
verificar_layout.setVisibility(View.INVISIBLE);
layout_activado = false;
pulsado = false; }
else{
Intent intent_cancelar = new Intent(PublicarActivity.this, Principal_Activity.class);
startActivity(intent_cancelar);
}
}
How could I do exactly this from my fragment?
There are two things in your question to be solved to get you the answer.
First thing is confusion between Activity and Fragment. You might have encountered an statement -"Activity represents single screen" in Android. So having Activity in your application will let your user interact with various views such as buttons, lists etc. So now, let's consider an instance when you want to add such a view in your Activity which should contain some state lifecycle (like you can have list in fragment and clicking on item should lead you to detailed view in the same view) so that you can have mini-Activity in your main activity while all other components remaining at the same positions. So providing functionalities like mini-activity your Fragment is going to have some life-cycle methods which will be called during Fragment Life time. So you can use Fragment whenever you feel you want some sub-Activity in your main Activity or for any other use. You can cover your whole Activity with Fragment as we mostly do whenever we want to have Navigation-Drawer in our app.
Now that you have got clear about Fragment and Activity( I hope so) you can refer to the link provided by person named cricket which is this.

Converting Activity to Fragment

I am converting an activity to a fragment so that I can use it within the Android Studio Navigation Drawer template.
I have changed all my activities to extend from fragment, and ensured that I am importing v4 support for fragments.
I have resolved most of the issues that Android Studio has raised...but I am really stuck on the final issue:
I have a fragment that used to be the mainActivity (now called liveview_fragment.java), which calls a class called ApplicationController in a file called ApplicationController.java. However, the line in liveview_fragment that calls ApplicationController gives the following error:
I am new to android/java, with most of my learning coming from tutorials and trial/error. Please could someone point out what I have missed in order to resolve this issue?
Thanks
You'll probably need to pass a context to the ApplicationController. Try with getActivity() or getContext() instead of this
The problem is that liveview_fragment is now a Fragment instead of an Activity. In order to get the hosting Activity, you can call getActivity(). This will probably fix the error.
Always use the getActivity() method to get the context of your attached activity, but always remember one thing: Fragments are slightly unstable and getActivity returns null some times, so for that, always check the isAdded() method of fragment before getting context by getActivity() refer Using context in a fragment

Passing arraylist from multiple fragments to activity

I have a follow up question from my previous questions.
My app starts and fragment loads, it passes in the arraylist correctly using interface and listener method .. Now when I click on navigation button to replace current fragment with another fragment... That fragment is exactly the same as first fragment but with different array list... How would I update the arraylist in activity?
I get a classcast exception.
Here are how both of my fragments are implemented
Pass Arraylist from fragment to its own Activity
In terms of the ClassCastException, did you make sure to have your MainActivity(know its MainActivity from MainActivity.java:107) implement the OnFragmentInteractionListener? If you don't that could be why you're getting that ClassCastException, because you're trying to cast your an activity instance(getActivity) to a subclass of which it does not share any inheritance relationship with (OnFragmentInteractionListener)

Fragments onClick method in fragment element

I read quite some articles about fragments, but I am still confused about how to do what.
I have a MainActivity, which displays two fragments side by side. In one of the fragments I have a button and defined in the fragments layout XML for the button
android:onClick="buttonClicked"
Now I want to implement that method
public void buttonClicked(View view)
I would have assumed that this has to be implemented in FragmentA.java and not in MainActivity.java. But it only works if that method is implemented in MainActivity.java. Why is that? To me that doesn't make sense. Pre Honeycomb a method belonging to one activity stayed in that activity, now on a tablet I am merging many activities to one MainActivity and all the different methods are merged? Whatever do you put for example in FragmentA.java then? What if you have to start you an own activity because this app runs on a handheld, then the onClick method has not to be in the MainActivity but in the Activity which needs to be called then. I am pretty confused at the moment...
I'm not sure what the specific problem is, but maybe this will help.
From the Android documentation on Fragments:
You should design each fragment as a modular and reusable activity component. That is, because each fragment defines its own layout and its own behavior with its own lifecycle callbacks, you can include one fragment in multiple activities, so you should design for reuse and avoid directly manipulating one fragment from another fragment.
That is, you should never manipulate a fragment from another fragment; rather, this should be done through the underlying Activity. Read the "Creating event callbacks to the activity" section in this article for more information (it's important stuff!!).
On the other hand, if you want the button to perform an action within the Fragment itself (i.e. if you wanted a Button click to change the text of a TextView within the Fragment), you should implement this in the Fragment, not the Activity (this is because the resulting behavior is contained within the Fragment and has nothing to do with the parent Activity).
Leave a comment and I can clarify if my post is confusing... I only recently began to understand Fragment's myself :).
Well,
I guess it is related to hierarchy of android context structure.
Activity is host of all child views and hence you can say fragment is actually using its host's context.And that's why when you use onClick with fragment system always searches it in Host activity of fragment.
Check it on.
Android developer onClick attribute description
I haven't checked one thing but you could put a test.
By providing implementation in host activity rather than in fragment,but use onClick on layout file of fragment.It should call parent's method.

Categories