Communication between fragment and Activity

Source: Internet
Author: User

 

I personally compare the communication between fragment and activity to the communication between JSP and Servlet. Fragment uses interfaces to communicate with activity. The communication result can be passed into another fragment as data. Of course, two fragment systems can also communicate with each other ~

Note: When loading or switching fragment, you must create a new fragmenttransaction object. You cannot use the same fragmenttransaction object to replace the container or add fragment. You can add the fragment to the container by filling the two containers with two fragment objects ):

Fragmentmanager = getsupportfragmentmanager (); fragmenttransaction Ft = fragmentmanager. begintransaction (); ft. settransition (fragmenttransaction. transit_fragment_fade); ft. add (R. id. container_fragment, new myfragment ()). commit (); // The same fragmenttransaction cannot be used to load two fragment fragmentmanagers. begintransaction (). add (R. id. container_fragment02, new myfragment02 ()). commit ();

 

The method for changing fragment is:

        getSupportFragmentManager().beginTransaction().        replace(R.id.container_fragment02, fragment)        .addToBackStack(null)        .commit();

 

In this example, after clicking the button in a fragment, fragment transmits a value to the activity, and the activity receives the value and transmits the value to another fragment (on the right) to change the content in the textview.

Activity_main.xml (defines two la s as fragment containers)

<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:background="#000000"    android:orientation="horizontal" >    <FrameLayout        android:id="@+id/container_fragment"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_weight="1"        android:background="#ffffff"        android:layout_marginRight="1dp" />    <FrameLayout        android:id="@+id/container_fragment02"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_weight="1"        android:background="#ffffff"        android:layout_marginLeft="1dp" >    </FrameLayout></LinearLayout>

 

Fragment. xml

<Relativelayout 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" tools: context = "$ {relativepackage }. $ {activityclass} "> <button Android: Id =" @ + ID/fragment_button "Android: layout_width =" wrap_content "Android: layout_height =" wrap_content "Android: layout_centerhorizontal =" true" "Android: layout_centervertical =" true "Android: layout_marginbottom =" 41dp "Android: text =" Kale "/> <textview Android: layout_width =" wrap_content "Android: layout_height = "wrap_content" Android: layout_above = "@ + ID/fragment_button" Android: layout_centerhorizontal = "true" Android: layout_marginbottom = "46dp" Android: TEXT = "click to upload the value" Android: textappearance = "? Android: ATTR/textappearancelarge "/> </relativelayout>

 

Myfragment

Package COM. kale. activity; import android. app. activity; import android. OS. bundle; import android. support. annotation. nullable; import android. support. v4.app. fragment; import android. util. log; import android. view. layoutinflater; import android. view. view; import android. view. viewgroup; import android. view. view. onclicklistener; import android. widget. button; public class myfragment extends fragment {private mycall Back mcallback; // define a call interface} public interface mycallback {public void onbtnclick (view V);} string tag = getclass (). getname (); @ override public void onattach (activity) {super. onattach (activity); log. E (TAG, "F ------------ onattach->"); If (! (Activity instanceof mycallback) {Throw new illegalstateexception ("the activity where fragment is located must implement the callbacks interface");} // treat the bound activity as the callback object mcallback = (mycallback) activity;} @ override public void onactivitycreated (@ nullable bundle savedinstancestate) {super. onactivitycreated (savedinstancestate); log. E (TAG, "F ------------ onactivitycreated->"); // The control must be initialized after the view is defined. The control cannot be placed in oncreat (). Button BTN = (button) getactivity (). findviewbyid (R. id. fragment_button); BTN. setonclicklistener (New onclicklistener () {@ override public void onclick (view v) {mcallback. onbtnclick (v) ;}}) ;}@ override public void ondetach () {super. ondetach (); log. E (TAG, "F ------------ ondetach->"); mcallback = NULL; // The amplitude before removal is null }}

 

Fragment02.xml

<? XML version = "1.0" encoding = "UTF-8"?> <Relativelayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: layout_width = "match_parent" Android: layout_height = "match_parent"> <textview Android: Id = "@ + ID/fragment_textview" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: layout_centerhorizontal = "true" Android: layout_centervertical = "true" Android: text = "null" Android: textappearance = "? Android: ATTR/textappearancelarge "/> <textview Android: layout_width =" wrap_content "Android: layout_height =" wrap_content "Android: layout_above =" @ + ID/fragment_textview "Android: layout_centerhorizontal = "true" Android: layout_marginbottom = "40dp" Android: textappearance = "? Android: ATTR/textappearancelarge "Android: text =" incoming information "/> </relativelayout>

 

Myfragment02

Package COM. kale. activity; import android. app. activity; import android. OS. bundle; import android. support. annotation. nullable; import android. support. v4.app. fragment; import android. util. log; import android. view. layoutinflater; import android. view. view; import android. view. viewgroup; import android. widget. textview; public class myfragment02 extends fragment {public static final string key = "key"; string tag = getclass (). getname (); @ override public view oncreateview (layoutinflater Inflater, @ nullable viewgroup container, @ nullable bundle savedinstancestate) {log. E (TAG, "F ------------ oncreateview->"); Return Inflater. inflate (R. layout. fragment02, container, false) ;}@ override public void onactivitycreated (@ nullable bundle savedinstancestate) {super. onactivitycreated (savedinstancestate); log. E (TAG, "F ------------ onactivitycreated->"); // The control must be initialized after the view is defined. The control cannot be placed in oncreat () textview TV = (textview) getactivity (). findviewbyid (R. id. fragment_textview); TV. settext ("Haha"); bundle = getarguments (); If (bundle = NULL) {TV. settext ("Default Value 01");} else {TV. settext (bundle. getstring (key, "Default Value 02 "));}}}

 

Source code download: http://download.csdn.net/detail/shark0017/7709315

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.