Fragment detailed five---fragment parameter transfer

Source: Internet
Author: User

Preface: There is still no preface ...


Related articles:

1, "One of fragment--Overview"
2, "fragment detailed two--basic use Method"
3, "fragment detailed three--management fragment (1)"
4, "fragment detailed four--management fragment (2)"
5, "Fragment details of the five--fragment between the transfer of parameters"
6, "fragment detailed six--how to monitor fragment in the fallback event and how to save the fragment status"


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. In the first case, a previous article was written detailing the previous fragment method of passing parameters to the next fragment, and data callbacks. See also: "Fragment transfer parameters and results return method"

Here's a closer look at these two parameter passing methods.
one, the same container between the parameters passed.

About this issue, please go to the previous write an article: "Fragment jump transfer parameters and results back to the method", in this article about the fragment jump parameter transfer and the results of the callback has been very clear, here there is no need to re-write again, here is the effect of this article diagram:

1, at the beginning of the interface, click on the "load the second Fragment" button 2, Fragment2, and passed to it a parameter "from the Fragment1 parameters", displayed in Fragment2 3, click on Fragment2 in the four small animals in one, The FRAGMENT1 will return the user click on which animal, in the Fragment1 display. It looks very interesting. Then take a look into this article.

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

Here is the main point 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 the effect diagram:
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=" @+id/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= "@+id/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>
</LinearLayout>
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"/>
    
</LinearLayout>
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.
The source code is given at the bottom of the article

It can be seen that the control of each fragment is implemented directly in the activity to achieve the message transmission. But, that's really good. If the controls in each fragment are operating in the activity, then what do you fragment do? 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. The question came, and each gained their own stuff, and what made 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 if the user forgets what to do. 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);
OK, here is the end of this article, the source came.

Reference article:

1, "Android fragments detailed five: communication with the activity"

2, "inter-fragment communication"


SOURCE content:

1, "Harvicblog5_1": Corresponding method one
2, "Harvicblog5_2": Corresponding method two

3, "Harvicblog5_3": Corresponding method Three


If this article has helped you, remember to pay attention to Oh

Source code Download address: http://download.csdn.net/detail/harvic880925/8582921

Please respect the original copyright, reproduced please indicate the source: http://blog.csdn.net/harvic880925/article/details/44966913, thank you.



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.