fragment-Passing parameters

Source: Internet
Author: User

There are two scenarios for the transfer of parameters between fragment:

    • First case: parameter passing between different fragment in the same container. This typically occurs when the fragment jumps, and the previous fragment passes the parameters to the next fragment.
    • Second case: Is the same activity, not a container between the fragment parameters passed.

The first case: the method of transferring parameters and returning the results fragment jump

1, click "Load the Second fragment button", load out the second fragment, while passing the past parameters: "From the Fragment1 parameters" these string;

2, when the user clicks on a few pictures in the second fragment, the result of the point is returned to the first fragment, the user's choice is displayed in the first fragment

First, the basic structure of the building

First of all, we need to build up the entire architecture and then pass and return the parameters.

(a), basic XML construction:

According to the above effect, it is easy to see the layout of two fragment:

1, the layout of Fragment1: (Fragment1.xml)

Very simple, vertical layout, above a imageview to dress up the results of the picture returned, the following button to click to load the second fragment;

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"      android:layout_width= "Match_ Parent "      android:layout_height=" match_parent "      android:background=" #ffffff "      android:orientation=" Vertical ">      <imageview          android:id=" @+id/img_result "          android:layout_width=" 100DP "          android: layout_height= "100DP"          android:scaletype= "center"/>        <button          android:id= "@+id/load_fragment2_ BTN "          android:layout_width=" fill_parent "          android:layout_height=" wrap_content "          android:text=" Load a second fragment "/>    </LinearLayout>  

2, the layout of Fragment2: (fragment2.xml)

This is also a vertical layout, above a textview used to dress up from the Fragment1 string parameters, the following several imageview to display several user-selectable pictures

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Match_parent" android:layout_height= "Match_parent" android:background= "#ffffff" android:orientation= "vertical" > < TextView android:id= "@+id/textview" android:layout_width= "Wrap_content" android:layout_height= " Wrap_content "android:text=" This is Fragment 2 "android:textcolor=" #000000 "android:textsize=" 2 5sp "/> <imageview android:id=" @+id/img1 "android:layout_width=" 100dip "Android:la           yout_height= "100DP" android:scaletype= "center" android:src= "@drawable/animal1"/> <imageview Android:id= "@+id/img2" android:layout_width= "100dip" android:layout_height= "100DP" an Droid:scaletype= "center" android:src= "@drawable/animal2"/> <imageview android:id= "@+id/img3 "Android:layouT_width= "100dip" android:layout_height= "100DP" android:scaletype= "center" android:src= "@drawabl E/animal3 "/> <imageview android:id=" @+id/img4 "android:layout_width=" 100dip "Andro id:layout_height= "100DP" android:scaletype= "center" android:src= "@drawable/animal4"/> </linearl   Ayout>

(ii) the corresponding fragment class

1. When the mainactivity is initialized, the Fragment1 is displayed:
mainactivity the corresponding XML file: (Main_activity.xml)

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"      xmlns:tools= "http// Schemas.android.com/tools "      android:id=" @+id/main_layout "      android:layout_width=" Match_parent      " android:layout_height= "Match_parent"      tools:context= ". Mainactivity ">        <textview          android:text=" @string/hello_world "          android:layout_width=" Wrap_ Content "          android:layout_height=" Wrap_content "/>    

The corresponding code:

public class Mainactivity extends Activity {        @Override      protected void onCreate (Bundle savedinstancestate) {          super.oncreate (savedinstancestate);          Setcontentview (r.layout.activity_main);          Fragment1 fragment1 = new Fragment1 ();          Getfragmentmanager (). BeginTransaction (). replace (R.id.main_layout, fragment1). commit ();      }  }  

2, Fragment1: When the user clicks, add fragment2 to the current page display;

public class Fragment1 extends Fragment {        @Override public      View Oncreateview (layoutinflater inflater, ViewGroup Container,                               Bundle savedinstancestate) {          View view = Inflater.inflate (R.layout.fragment1, container, false);          Button btn = (button) View.findviewbyid (R.ID.LOAD_FRAGMENT2_BTN);          Btn.setonclicklistener (New View.onclicklistener () {              @Override public              void OnClick (Final view view) {                  Fragment2 Fragment2 = new Fragment2 ();                                    Fragmenttransaction transaction = Getfragmentmanager (). BeginTransaction ();                    Transaction.add (R.id.main_layout, fragment2);                  Transaction.addtobackstack (null);                  Transaction.commit ();              }          });          return view;      }  }  

3, Fragment2: As for the current it is very simple, as long as it can be displayed, so his code is:

public class Fragment2 extends Fragment implements View.onclicklistener {        @Override public      View Oncreateview ( Layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {          View view = Inflater.inflate ( R.layout.fragment2, container, false);          return view;      }    

Second, the parameter transfer between fragment

In Fragment2, create a new function: newinstance (String text) to receive the passed arguments:

Create a new Fragment2 instance, and then set the parameters through setarguments;

public static Fragment2 newinstance (String text) {      Fragment2 fragment = new Fragment2 ();      Bundle args = new bundle ();      Args.putstring ("param", text);      Fragment.setarguments (args);      return fragment;  }  

Then get the parameters from the arguments in the Fragment2 Oncreateview:

public view Oncreateview (Layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {      View view =  Inflater.inflate (R.layout.fragment2, container, false);      if (getarguments () = null) {          String mParam1 = getarguments (). getString ("param");          TextView TV =  (TextView) View.findviewbyid (R.id.textview);          Tv.settext (MPARAM1);      }      return view;  }  

In Fragment1, when FRAGMEN2T is invoked, the Newinstance function is called to fetch the instance and pass the arguments:

public class Fragment1 extends Fragment {        @Override public      View Oncreateview (layoutinflater inflater, ViewGroup Container,                               Bundle savedinstancestate) {          View view = Inflater.inflate (R.layout.fragment1, container, false);          Button btn = (button) View.findviewbyid (R.ID.LOAD_FRAGMENT2_BTN);          Btn.setonclicklistener (New View.onclicklistener () {              @Override public              void OnClick (Final view view) {                  Fragment2 Fragment2 = fragment2.newinstance ("Parameters coming from Fragment1");                    Fragmenttransaction transaction = Getfragmentmanager (). BeginTransaction ();                  Transaction.add (R.id.main_layout, fragment2);                  Transaction.addtobackstack (null);                  Transaction.commit ();              }          });          return view;      }  }  

(iii), from the Fragment2 to the Fragment1 callback parameters

Here is only the callback, the question about the callback pass parameter, I in the previous article: "Detailed dialog (three)--custom dialog box view and parameter passing" Part III: Parameter transmission; In detail, we can first look at the source code, if the source does not understand, you can refer to this article, here will not repeat.

Second case: parameter transfer of fragment between different container

Second, the same activity, the parameter transfer between different container

Here to the main content of this article Oh, this is not to say that the last part is not important ha, in fact, the last part is more important than this part! The parameters between different fragment in the same container will be used in general engineering, so we must look at them. And I do not speak here, because there have been said before, there is no need to repeat it, well, nonsense said a lot ... Open the whole bar.
First Look at:
1, there are two fragment in this actiivty;
2, Fragment1 has a ListView, when we click on the ListView item, the item content on the update to Fragment2

Here are a number of implementations, preferably method three. We are from Jane to easy to speak slowly.
We want to enable two fragment instances to be able to communicate, so if we can all find all the controls through Findviewbyid (), we will not be able to manipulate them directly. The place where all control instances can be found through Findviewbyid () is in activity, so there is a method.

method One: Operate directly in the activity

Find the corresponding control instance in the activity and manipulate it directly.
First look at the layout of mainactivity: Activity_main.xml

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android      "Android:id=" @+id/main_layout "android:layout_width=" match_parent "android:layout_height=" Match_parent " android:orientation= "Horizontal" android:baselinealigned= "false" > <fragment android:id= "@+i          D/fragment1 "Android:name=" Com.harvic.com.harvicblog5_1.Fragment1 "android:layout_width=" 0dip " android:layout_height= "Match_parent" android:layout_weight= "1"/> <fragment android:id= "@+i          D/fragment2 "Android:name=" Com.harvic.com.harvicblog5_1.Fragment2 "android:layout_width=" 0dip " android:layout_height= "Match_parent" android:layout_weight= "1"/> </linearlayout> 

In this layout, the horizontal placement of two fragment, because here the fragment is statically added, so each fragment has an ID value, so this time if we want to get a fragment instance, we can through Fragmentmanager:: Findfragmentbyid () to find out.
Then there is the layout of these two fragment.
Fragment1.xml:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"      android:layout_width= "Match_ Parent "      android:layout_height=" match_parent "      android:background=" #ff00ff "      android:orientation=" Vertical ">            <textview          android:layout_width=" wrap_content "          android:layout_height=" wrap_content "          android:text=" This is fragment 1 "          android:textcolor=" #000000 "          android:textsize=" 25sp "/>        <listview          android:id= "@+id/list"          android:layout_width= "match_parent"          android:layout_height= " Match_parent "></ListView>  

You can see the layout of fragment1, in addition to a textview that identifies the current fragment, is a ListView;
Fragment2.xml:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"      android:layout_width= "Match_ Parent "      android:layout_height=" match_parent "      android:background=" #ffff00 "      android:orientation=" Vertical ">            <textview          android:id=" @+id/fragment2_tv "          android:layout_width=" Wrap_content          " android:layout_height= "Wrap_content"          android:text= "This is Fragment 2"          android:textcolor= "#000000"          Android:textsize= "25SP"/>        

You can see that the fragment2 is very clean and there is only one textview to display the results of the current user's click in Fragment1.
Let's see how it's implemented in mainactivity.

protected void OnCreate (Bundle savedinstancestate) {      super.oncreate (savedinstancestate);      Setcontentview (r.layout.activity_main);        Arrayadapter arrayadapter = new Arrayadapter<string> (this,android. r.layout.simple_list_item_1,mstrings);      ListView ListView = (ListView) Findviewbyid (r.id.list);      Listview.setadapter (arrayadapter);        MFRAGMENT2_TV = (TextView) Findviewbyid (R.ID.FRAGMENT2_TV);        Listview.setonitemclicklistener (New Adapterview.onitemclicklistener () {          @Override public          void Onitemclick ( Adapterview<?> Parent, view view, int position, long id) {              mfragment2_tv.settext (mstrings[position]);          }      });  }  

which

Private string[] Mstrings = {"Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "abondance", "Ackawi", "Acorn",          "Adelost", "Affidelice au Chablis", "Afuega ' L Pitu", "Airag", "Airedale", "Aisy cendre",          "Allgauer Emmentaler", "Abba Ye de Belloc "," Abbaye du Mont des Cats "," Abertam "," abondance "," Ackawi ",          " Acorn "," Adelost "," Affidelice au Chablis "," Afuega ' L Pitu "," Airag "," Airedale "," Aisy cendre ",          " Allgauer Emmentaler "};  

Difficulty, through (ListView) Findviewbyid (r.id.list); Find the Fragment1 in the ListView, Through (TextView) Findviewbyid (R.ID.FRAGMENT2_TV); Locate the TextView in the Fragment2, and then directly manipulate them. That is, the following code:

Listview.setonitemclicklistener (New Adapterview.onitemclicklistener () {      @Override public      void Onitemclick ( Adapterview<?> Parent, view view, int position, long id) {          mfragment2_tv.settext (mstrings[position]);      }  });  

When the user taps an item in the ListView, the value is settext to the Fragment2 TextView.

It can be seen that the control of each fragment is implemented directly in the activity to achieve the message transmission. But, is this really good? If the controls in each fragment are operating in the activity, why fragment? At the very least, each fragment should be responsible for its own control operations.
So, we've improved on this approach by placing the assignment of the item on the FRAGMENT1. So, there is the method two;

Method Two: Operate directly in the fragment

Here we will write all the methods in Fragment1, here are two aspects of the content:
First: How to get a reference to your control in fragment, compare the ListView control in Fragment1 here.
Second: How to get references to controls in other fragment pages in fragment, such as the TextView controls in Fragment2 here.
First, get the method that your control references:
method One: obtained in Oncreateview ().
Just like here to get a reference to your ListView control, the code is as follows:

Public View Oncreateview (layoutinflater inflater, ViewGroup container,          Bundle savedinstancestate) {      view Rootview = Inflater.inflate (R.layout.fragment1, container, false);      ListView = (ListView) Rootview.findviewbyid (r.id.list);//Gets the control reference in its own view, method one      return rootview;  }  

Since the view has not been created in Oncreateview (), the use of the GetView () method here will return null. So if you want to get a reference to the specified control in the diagram, use only the Rootview returned with Inflater.inflate (), and in this rootview () use Findviewbyid to find it.
Method Two: Obtained in the onactivitycreated () function.
As you can see from the flowchart of one of the fragment-Overview, the onactivitycreated () callback is executed after the activity's OnCreate () is completed, that is, onactivitycreated () will not be executed until the OnCreate () work of the activity is completed. So when executing to onactivitycreated (), the activity has been created, and its various fragment views, and so on, have been created. Where you can get all the resources related to your activity. The second problem is to get references to the controls in the other fragment pages are also done in onactivitycreated (). Let's take a look at how to get a reference to a control in your own view in onactivitycreated ().

public void onactivitycreated (Bundle savedinstancestate) {      super.onactivitycreated (savedinstancestate);        ListView = (ListView) GetView (). Findviewbyid (r.id.list);//Get the control reference in your own view, method two  }   

then, get the other methods that fragment the controls in the page
As already stated above, to get the resources in the activity, you must wait for the acitivity creation to complete, so you must put it in the onactivitycreated () callback function.
It is obtained by:

public void onactivitycreated (Bundle savedinstancestate) {      super.onactivitycreated (savedinstancestate);        MFRAGMENT2_TV = (TextView) getactivity (). Findviewbyid (R.ID.FRAGMENT2_TV);//The only way to get control references in other fragment!!!    }  

After a bunch of the above, let's look at how it's done in Fragment1.
As we can tell from the above, it is possible to get a reference to a control in your own view or to get a reference to a control in another fragment in the onactivitycreated () function, so we put them all in onactivitycreated ().

public void onactivitycreated (Bundle savedinstancestate) {      super.onactivitycreated (savedinstancestate);        MFRAGMENT2_TV = (TextView) getactivity (). Findviewbyid (R.ID.FRAGMENT2_TV);//The only way to get control references in other fragment!!!      ListView = (ListView) GetView (). Findviewbyid (r.id.list);//Get the control reference in your own view, method two        arrayadapter arrayadapter = new Arrayadapter<string> (Getactivity (), Android. R.layout.simple_list_item_1, mstrings);      Listview.setadapter (arrayadapter);      Listview.setonitemclicklistener (New Adapterview.onitemclicklistener () {          @Override public          void Onitemclick ( Adapterview<?> Parent, view view, int position, long id) {              String str = mstrings[position];              Mfragment2_tv.settext (str);          }      );  }  

It is not very difficult, it is also obtained after each control, directly to them to operate.

The source code is given at the bottom of the article

We operate the Fragment2 control directly in the Fragment1, which violates the idea of module separation, and we should let them handle their own code well. So, considering separating them, we've got method three here.

method Three: Operate in the respective fragment

Well, first of all, let's think about how we can solve this problem, firstly, we put our respective events in our own fragment, that is, the string string of item that can be clicked by the current user in Fragment1, and the value of TextView is set in Fragment2. That's the question, and each of them gets their own stuff, and what makes them interact?
The answer is obviously activity.
Obviously, you can get an instance of Fragment2 directly from Fragmentmanager::findfragmentbyid () in activity. And then call any method in Fragment2, which realizes the communication with the Fragment2.
And how did the Fragment1 return the results to the activity? If you look at this before you see the "Fragment Jump transfer parameters and results return method" It is easy to think, with a callback! Please remember. Callbacks are a versatile solution for returning results from different pages.
1. Fragment2 Set TextView function:
First look at a simple, fragment2 in the processing code:

public class Fragment2 extends Fragment {      private TextView mTv;      ....... public void SetText (String text) {          mtv.settext (text);      }  }  

2, Fragment1 in the processing mode:
(1), defining interfaces and variables
Since the callback is used, first define an interface and the corresponding variable:

Private Titleselectinterface mselectinterface;     Public interface titleselectinterface{public      void Ontitleselect (String title);    

(2), interface variable assignment
Interfaces are for activity, so there are many ways to assign values to the interface variables in the activity, and of course you can choose to write a setxxx () function to assign values, but what if the user forgets? So we're forcing the user to assign a value. Therefore, a strong transfer method is used when the fragment is associated with activity, and the value is strongly transferred:

public void Onattach (activity activity) {      Super.onattach (activity);        try {          mselectinterface = (titleselectinterface) activity;      } catch (Exception e) {          throw new ClassCastException (activity.tostring () + "must implement Onarticleselectedlistener");      }  

The problem with a strong-turn approach is that if the user's activity is not implements Titleselectinterface, it throws an error, so it will be discovered during debugging.
(3), calling interface variables
The next step is to pass the results back to the activity in Fragment1 when the user clicks on the ListView item, as follows:

public void onactivitycreated (Bundle savedinstancestate) {      super.onactivitycreated (savedinstancestate);        ListView = (ListView) GetView (). Findviewbyid (r.id.list);//Get the control reference in your own view, method two      arrayadapter arrayadapter = new Arrayadapter<string> (Getactivity (), Android. R.layout.simple_list_item_1, mstrings);      Listview.setadapter (arrayadapter);      Listview.setonitemclicklistener (New Adapterview.onitemclicklistener () {          @Override public          void Onitemclick ( Adapterview<?> Parent, view view, int position, long id) {              String str = mstrings[position];              Mselectinterface.ontitleselect (str);          }      );  }  

(4) Implementation of Titleselectinterface interface in activity
The first is that the mainactivity must implement the Titleselectinterface interface, and the result will be returned in Ontitleselect (String title), with Fragment2.settext () after the result is returned Operation TextView; code as follows:

public class Mainactivity extends Fragmentactivity implements Fragment1.titleselectinterface {        ...            @Override public      void Ontitleselect (String title) {          Fragmentmanager manager = Getsupportfragmentmanager ();          Fragment2 Fragment2 = (Fragment2) Manager.findfragmentbyid (r.id.fragment2);          Fragment2.settext (title);      }  }  

As can be seen in the above code, after the result is returned, through Findfragmentbyid () to obtain an instance of Fragment2, here for the first time the use of Findfragmentbyid () function, which is mainly used to statically add fragment, Gets an instance of it by using the ID value of the fragment. After obtaining an instance of Fragment2, we wrote the SetText () method by calling us to display the results in TextView.

Fragment2 Fragment2 = (Fragment2) Manager.findfragmentbyid (R.id.fragment2);  

fragment-Passing parameters

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.