Fragment data transfer, transmit value, communication

Source: Internet
Author: User

[Original] "Fragment-depth Series 4" Fragment data interaction with activity

2015-5-26 Read 389 comments 0

The following is from your own practice and the collation of network materials, I hope to help you.

First, the activity to pass the value to fragment

The recommended way of passing is through bundles, not directly as fragment construction parameters. Bundle packets can be passed to fragment by creating bundle packets in activity and invoking fragment's setarguments (Bundle bundle) method. Use the Getarguments method in fragment to get the value passed in.

Second, fragment pass the value to the activity

Define an internal callback interface in fragment, and then let the activity that contains the fragment implement the callback interface so that fragment can invoke the callback method to pass the data to the activity. In fact, the principle of interface callback is the same, the previous blog has said that interface callback is the Java different objects of data interaction between the common method.

  The activity is done. How to pass the interface to the fragment just now ? When fragment is added to the activity, the Fragment Method Onattach () is called, which is suitable for checking that the activity implements the Onarticleselectedlistener interface. The check method is to type-Convert the instance of the incoming activity, and then assign a value to the interface that we defined in fragment.

When a fragment is stripped from activity, it calls the Ondetach method, which releases the activity object that is passed in, otherwise it will affect the destruction of the activity, resulting in unnecessary errors. Note The code in the Onattach method, before assigning a value to make a judgement, see if there is any implementation of this interface in the activity, the use of instanceof. If the interface is not implemented, we throw an exception.

Example: Add a bunch of buttons to the left, click to the left, then the right content changes

Fragment writing
Package com.stady.hg.demos.fragmentinteraction;Import android.app.Activity;Import android.app.Fragment;Import Android.os.Bundle;Import Android.view.LayoutInflater;Import Android.view.View;Import Android.view.ViewGroup;/** * Created by Intellij idea * project:fragmentinteraction * AUTHOR:HG * email:[email protected] * DATE:2015/4/30 * *PublicClassMenufragmentExtendsFragmentImplementsView.Onclicklistener {/** * used to interact with external activity */Private Fragmentinteraction Listterner;PublicMenufragment () {}/** * will be recalled when Fragmen is loaded into activity *@param activity */@OverridePublicvoidOnattach (activity activity) {Super.onattach (activity);if (activityinstanceof fragmentinteraction) {Listterner = (fragmentinteraction) activity;}else{ThrowNew IllegalArgumentException ("Activity must implements Fragmentinteraction"); } }@OverridePublicvoidOndetach () {Super.ondetach (); Listterner =Null }/** * Defines the interfaces that all activity must implement */PublicInterfacefragmentinteraction {/** * Fragment The instructions to the activity, this method can be defined according to the requirements *@param STR */void process (String str); }@OverridePublic ViewOncreateview (Layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {View view = Inflater.inflate ( R.layout.fragment_menu, Container,FALSE); View btn = View.findviewbyid (R.id.tv_button); View btn_m = View.findviewbyid (R.id.movie_button); View Btn_c = View.findviewbyid (R.id.comic_button);if (btn! =null| | btn_m!=null| | btn_c!=NULL) {Btn.setonclicklistener (this); Btn_m.setonclicklistener (this) Btn_c.setonclicklistener (return view;}  @Override public void onclick (View v) {int id = v.getid (); switch (ID) {case r.id.tv_button:listterner.process ( "I am a TV show"); break; case r.id.movie_button:listterner.process ( "I am a movie"); break; case r.id.comic_button:listterner.process ( "I am anime"); break; } }} 

!!!

Notice that in the Ondetach method, the activity passed in is released.

Activity writing
Package com.stady.hg.demos.fragmentinteraction;Import android.app.Activity;Import Android.os.Bundle;Import Android.widget.TextView;PublicClassMainactivityExtendsActivityImplementsMenufragment.fragmentinteraction{Private TextView TextView;/** * Called when the activity is first created. */@OverridePublicvoid oncreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main); TextView = (TextView) Findviewbyid (R.id.content_text); } /** * to Fragment call * @param str */ //public void SetContent (String str) //{//if (str!=null) //{//textView.setText (str); //} //}  @Override public void process (String str) {if (str! = null) { Textview.settext (str); } }}  
Third, the value of fragment and fragment

When loading fragment in activity, sometimes to use multiple fragment to switch, and transfer value to another fragment, that is, two fragment between the parameters of the transfer, a lot of data, found two methods.

1, through the common activity transmission

This method is to add a field to the activity, to temporarily save some values. Define a field in the activity, then add the set and get methods, code as follows, Mtitle is the argument to pass, if it is a transitive object, you can change the Mtitle to an object.

public class DemoActivity {    private String mTitle;    public String getmTitle() { return mTitle; } public void setmTitle(String title) { this.mTitle = title; }}

Fragment call method, it should be noted that when setting the value of a strong turn

((DemoActivity)getActivity()).getmTitle();
2, through the bundle to pass

You can use bundles for parameter passing, so that you can take parameters when you jump two fragment, and you can also pass a complex object.

Ft.hide (getactivity () .getsupportfragmentmanager ( ) .findfragmentbytag (; Demofragment demofragment = new Demofragment () .putstring ( "key",  "This is method two")  Demofragment.setarguments (bundle) .add (R .id.fragmentroot, Demofragment, SEARCHPROJECT) Span class= "hljs-comment" >; Ft.commit ()        

In the other fragment the way to get the parameters only need a statement, key is its own definition of an identity, the form of parameters as long as the bundle can be passed can be implemented

String string = getArguments().getString("key");  

From the above two methods, the method of a simple, but personally feel a bit opportunistic, but also very close to Java development specifications, if it is the same activity to load a lot of fragment, this method is undoubtedly much simpler. The second method is to use the Android bundle transfer, this method should be more official, but in the project development, how to achieve simple, and not much relationship.

Iv. more references

In-depth analysis: several ways in which fragment interacts with activity (using handler): http://blog.csdn.net/huangyabin001/article/details/35231753 (In fact, this is also the idea of interface callbacks)

Fragment data transfer, transmit value, communication

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.