android-How to resolve interactions between fragment through interface callbacks

Source: Internet
Author: User

Since the fragment and acitivty of the silk thread mechanism on Android are instantiated into two unrelated objects, their connection is maintained by a member object Fragmntmanager the activity, Fragment instantiation into the activity of the Fragmentmanager to register, this action is encapsulated in fragment object Onattach, so you can declare some callback interface in fragment, When fragment calls Onattach, these callback interfaces are instantiated so that fragment can invoke the member functions of each acivity, and of course the activity must implements these interfaces, Otherwise it will be reported classcastexceptionfragment and activity callback mechanism is another perfect interpretation of OOP!

Here's an example to illustrate

The purpose of the implementation: to divide an activity with two fragment, the left side of the fragment has 3 buttons, the right side as the content display, when clicked on the left side of the button to display the corresponding text message.

The first is the Activity_main.xml layout file.

<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"     xmlns: tools= "Http://schemas.android.com/tools"     android:layout_width= "Match_parent"      android:layout_height= "match_parent"     android:orientation= "Horizontal"     tools:context= ". Mainactivity ">    <FrameLayout         Android:id= "@+id/ui_container"         android:layout_width= "0DP"          android:layout_height= "Match_parent"          android:layout_weight= "1" >    </FrameLayout>     <framelayout        android:id= "@+id/details_container"          android:layout_width= "0DP" &NBSP;&NBSP;&NBSP;&NBSP;&Nbsp;   android:layout_height= "Match_parent"          android:layout_weight= "1"         android:background= "@android: color/ Holo_blue_light ">    </FrameLayout></LinearLayout>

As shown below:

The fragment layout left_fragment.xml to the left is as follows:

<?xml version= "1.0"  encoding= "Utf-8"? ><linearlayout xmlns:android= "http// Schemas.android.com/apk/res/android "    android:orientation=" vertical " android:layout _width= "Match_parent"     android:layout_height= "Match_parent" ><Button     android:id= "@+id/firstbutton"     android:layout_width= "Wrap_content"      android:layout_height= "Wrap_content"     android:text= "@string/first_ Button "/><button    android:id=" @+id/secondbutton "    android: Layout_width= "Wrap_content"     android:layout_height= "Wrap_content"      android:text= "@string/second_button"/><button    android:id= "@+id/thenButton"     android:layout_width= "wrap_content"     android:layout_height= "wrap _content "    android:text= "@string/then_button"/></linearlayout> 

As shown below:

The fragment layout on the right is right_fragment.xml as follows:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "android:orientation=" vertical "android:layout_width=" match_parent "android:layout_height=" Match_parent "& Gt;<textview android:id= "@+id/content" android:layout_width= "match_parent" android:layout_height= "match_parent "/></linearlayout>


The above layout file is very simple, there is nothing to say, below, I will be the Java file code to explain the corresponding:

First the Leftfragment.java

package learn.dreamcoder.com.learn;import android.app.activity;import android.app.fragment; import android.graphics.color;import android.os.bundle;import  android.support.annotation.nullable;import android.view.layoutinflater;import android.view.view; import android.view.viewgroup;import android.widget.button;/** * description: *  User: dream_coder ([email protected])  * date: 2015-07-29 * time: 15:15  */public class LeftFragment extends Fragment{    public  Interface mylistener{        public void showmessage ( Int index);    }    private mylistener mlistener;     private Button mButton1;    private Button mButton2;     private button mbutton3;    public button lastbutton;     @Override      public void onattach (activity activity)  {/* determines whether the host Activity implements the interface mylistener*/         super.onattach (activity);         try {            mlistener =   (MyListener)  activity;        }catch  ( Classcastexception e)  {            throw  new classcastexception (Getactivity (). GetClass (). GetName ()                      + " must implements  interface mylistener ");         }    }      @Nullable &NBSP;&NBsp;   @Override     public view oncreateview (layoutinflater  Inflater, viewgroup container, bundle savedinstancestate)  {         view view = inflater.inflate (R.layout.left_fragment,container,false);         return view;    }      @Override     public void onresume ()  {         super.onresume ();        mbutton1 =  ( Button)  getactivity (). Findviewbyid (R.id.firstbutton);         mbutton2 =  (Button)  getactivity (). Findviewbyid (R.id.secondbutton);         mButton3 =  (Button)  getactivity (). Findviewbyid (R.id.thenbutton);        &nbsP;mbutton1.setonclicklistener (New mybuttonclicklistener ());         mbutton2.setonclicklistener (New mybuttonclicklistener ());         mbutton3.setonclicklistener (New mybuttonclicklistener ());    }     class MyButtonClickListener implements View.OnClickListener{          @Override         public void  OnClick (VIEW&NBSP;V)  {            button  button =  (Button)  v;             if (lastbutton != null)  {                 lastbutton.setbackgroundcolor (0);             }            button.setbackgroundcolor (Color.parseColor (" #00FF00 "));            lastbutton= button;             if (Button == mbutton1)   {                 Mlistener.showmessage (1);            }             if (Button == mbutton2)  {                  Mlistener.showmessage (2);            }             if (Button == mbutton3)  {           &nBsp;     mlistener.showmessage (3);             }        }    }}

The MyListener in this file is the key to this interaction process, exposing the interface to the host activity to implement, and the host activity implements the interface, according to the parameters passed in, make the appropriate operation, and issue the proper command to the second fragment, This allows you to change the state of the components in the second fragment.


The whole process can be understood as: Fragement1----"Activity-----" Fragment2

Fragment generally do not interact directly with each other, but need to use the host activity as a bridge to make calls.

The host activity is responsible for the business call between the fragement, and fragment is only responsible for maintaining its own component state, which requires the part of the business operation to be exposed to the host to do, and this exposure process is through the interface.


For example, in the code above, the Mlistener.showmessage () function is required in class Mybuttonclicklistener to present the information in Fragment2, but there is no statement in the fragment to implement the interface. It is used directly, because our aim is not to interact directly with Fragment2, but we can deliver this interface to the host activity, let it be implemented, let it do all this, and so, for leftfragment, don't worry about this problem, It's OK to use it directly, because the host has solved it all.

The Mainactivity.java code is explained below:

package learn.dreamcoder.com.learn;import android.app.activity;import  Android.app.fragmentmanager;import android.app.fragmenttransaction;import android.os.bundle;import  android.view.view;import android.widget.textview;import android.widget.toast;public class  MainActivity extends Activity implements LeftFragment.MyListener{     private TextView showMessageView;     @Override      Public void oncreate (bundle savedinstancestate)  {         super.oncreate (savedinstancestate);         setcontentview ( R.layout.activity_main);         fragmentmanager manager =  getfragmentmanager ();        fragmenttransaction  Transaction = manager.begintransaction ();  &nbSp;      transaction.add (R.id.ui_container,new leftfragment ());         transaction.add (R.id.details_container,new rightfragment ());         transaction.commit ();    }      @Override     public void showmessage (int index)  {         if (1 == index)  {             showmessageview.settext (r.string.first_page);         }else if (2 == index)  {             showmessageview.settext (r.string.second_page);         }else {             Showmessageview.settext (r.string.then_page);         }    }     @Override     protected void onresume ()  {         super.onresume ();        showmessageview =  (TextView)  findviewbyid (r.id.content);     }}


The first thing to do in the host activity is to implement the interface just now, and the purpose of this interface is to give the rightfragment a command to change its contents according to the parameters that were just exposed. So to get a reference to the TextView shown in Rightfragment, then set the text. That's a good understanding.

Here's Rightfragment.java.

Package learn.dreamcoder.com.learn;import android.app.fragment;import android.os.bundle;import  android.support.annotation.Nullable;import android.view.LayoutInflater;import  Android.view.view;import android.view.viewgroup;/** * description: * user: dream _coder ([email protected])  * date: 2015-07-29 * time: 15:16 */public  class RightFragment extends Fragment{     @Override      public void oncreate (bundle savedinstancestate)  {         super.oncreate (savedinstancestate);     }    @ nullable     @Override     public view oncreateview ( Layoutinflater inflater, viewgroup container, bundle savedinstancestate)  {         return  Inflater.inflate (r.layout.right_fragment,container,false);     }} 

This is very simple, there is nothing to say, I believe you can understand. Will not explain.

To sum up, for the interaction between the two fragment, if you want to send a request to fragment, directly encapsulate the request into an interface, exposed, to the host to achieve it.


I just for the sake of learning and understanding, feel this code is very meaningful, but not too much explanation, I wrote some comments according to their own understanding.

Thank the original author here

The original address of the article: http://www.360doc.com/content/14/0519/10/17121610_378958268.shtml


android-How to resolve interactions between fragment through interface callbacks

Related Article

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.