Brief introduction:
Why do you use fragment? Using fragment, you can implement different interfaces in one activity. The animation switch between fragment and fragment is much more varied than the animation switch between activity and activity. Many times, we switch multiple fragment by using an activity. This blog, the main list of fragment and its activity to exchange data between the way.
The public method in the activity is invoked in 1.Fragment by Getactivity () and then by a forced conversion
((xxxxactivity) getactivity ()). Fun ();
2.Activity when switching fragment, pass parameters to fragment via setarguments, fragment through Getarguments (), get values passed from activity
3.Activity implements an interface, fragment in the Onattach method, transforms the activity into that interface, and callbacks when calls are required.
Note: This demo is managed by Fragmentmanager to manage fragment, through Fragmentmanager management, we create fragment and destroy fragment by the way of the stack:
A.fragmenttransaction Add method, adding a fragment
B.fragmenttransaction's Popbackstack () pops up the fragment
Demo Example:
Fragment1.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 "android:backg Round= "#FFFFFFFF" android:paddingbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_ Horizontal_margin "android:paddingright=" @dimen/activity_horizontal_margin "android:paddingtop=" @dimen/activity_ Vertical_margin "tools:context=" com.example.testfragment.mainactivity$placeholderfragment "> <TextView Android:id= "@+id/tv" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android : layout_alignparenttop= "true" android:text= "Fragment1"/> <button android:id= "@+id/btn" Android Oid:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:layout_below= "@id/tv" an droid:text= "Jump to Fragment2"/></relativelayout>
Myfragment1.java
/* * $filename: MYFRAGMENT.JAVA,V $ * $Date: 2014-5-16 $ * Copyright (C) Zhenghaibo, Inc. All rights reserved. * This software are made by Zhenghaibo. */package Com.example.testfragment;import Android.app.activity;import Android.os.bundle;import Android.support.v4.app.fragment;import Android.view.layoutinflater;import Android.view.view;import Android.view.view.onclicklistener;import android.view.viewgroup;import android.widget.button;/* * @author: Zhenghaibo *WEB:HTTP://BLOG.CSDN.NET/NUPTBOYZHB *mail: [email protected] *2014-5-16 Nanjing,njupt,China */ public class MyFragment1 extends Fragment {fragmentcallback fragmentcallback = null; Button btn; @Overridepublic View Oncreateview (layoutinflater inflater, ViewGroup container,bundle savedinstancestate) { View Rootview = inflater.inflate (R.layout.fragment1, container,false); btn = (Button) Rootview.findviewbyid (R.ID.BTN); Btn.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated MeThod stubfragmentcallback.callbackfun1 (null);}}); return Rootview;} @Overridepublic void Onattach (activity activity) {//TODO auto-generated method Stubsuper.onattach (activity); Fragmentcallback = (mainactivity) activity;}}
Fragment2.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 "android:backg Round= "#FFFFFFFF" android:paddingbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_ Horizontal_margin "android:paddingright=" @dimen/activity_horizontal_margin "android:paddingtop=" @dimen/activity_ Vertical_margin "tools:context=" com.example.testfragment.mainactivity$placeholderfragment "> <TextView Android:id= "@+id/tv" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android : layout_alignparenttop= "true" android:text= "Fragment2"/> <button android:id= "@+id/btn1" and Roid:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:layout_below= "@id/tv" a Ndroid:text= "Call activity directly"/> <buttonAndroid:id= "@+id/btn2" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Andro id:layout_below= "@id/btn1" android:text= "Callback activity"/></relativelayout>
Myfragment2.java
/* * $filename: MYFRAGMENT.JAVA,V $ * $Date: 2014-5-16 $ * Copyright (C) Zhenghaibo, Inc. All rights reserved. * This software are made by Zhenghaibo. */package Com.example.testfragment;import Android.app.activity;import Android.os.bundle;import Android.support.v4.app.fragment;import Android.view.layoutinflater;import Android.view.view;import Android.view.view.onclicklistener;import Android.view.viewgroup;import Android.widget.button;import android.widget.toast;/* * @author: Zhenghaibo *web:http://blog.csdn.net/nuptboyzhb *mail: [email protected] *2014-5-16 Nanjing,njupt,china */public class MyFragment2 extends Fragment {fragmentcallback fragmentcallback = null; Button btn1; Button btn2; @Overridepublic View Oncreateview (layoutinflater inflater, ViewGroup container,bundle savedinstancestate) {View Rootview = inflater.inflate (R.layout.fragment2, Container,false); Bundle data = getarguments ();//Get the value passed from Activity Toast.maketext (Getactivity (), data.getstring ("TEXT"), Toast.lengtH_short). Show (), btn1 = (Button) Rootview.findviewbyid (R.ID.BTN1); Btn1.setonclicklistener (new Onclicklistener () {@ overridepublic void OnClick (View v) {//calls directly to the method in activity ((mainactivity) getactivity ()). Changebuttoncolor ();}); BTN2 = (Button) Rootview.findviewbyid (R.ID.BTN2); Btn2.setonclicklistener (new Onclicklistener () {@Overridepublic void The mode of the OnClick (View v) {///callback fragmentcallback.callbackfun2 (NULL);}}); return Rootview;} @Overridepublic void Onattach (activity activity) {//TODO auto-generated method Stubsuper.onattach (activity); Fragmentcallback = (mainactivity) activity;}}
Callback Interface:
/* * $filename: FRAGMENTCALLBACK.JAVA,V $ * $Date: 2014-5-16 $ * Copyright (C) Zhenghaibo, Inc. All rights reserved. * This software are made by Zhenghaibo. */package com.example.testfragment;import android.os.bundle;/* * @author: Zhenghaibo *web:/ http BLOG.CSDN.NET/NUPTBOYZHB *mail: [email protected] *2014-5-16 Nanjing,njupt,china */public interface fragmentcallback {public void callbackFun1 (bundle arg);p ublic void callbackFun2 (bundle arg);}
Main.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 " android:paddingbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_ Horizontal_margin " android:paddingright=" @dimen/activity_horizontal_margin " android:paddingtop=" @dimen /activity_vertical_margin "> <button android:id=" @+id/btn " android:layout_width=" match_parent " android:layout_height=" wrap_content " android:layout_alignparentbottom=" true " android:text=" toggle "/> <relativelayout android:id=" @+id/rl_container " android:layout_width=" Match_parent " android:layout_height= "wrap_content" android:layout_above= "@id/btn"/></relativelayout>
Mainactivity.java
Package Com.example.testfragment;import Android.graphics.color;import Android.os.bundle;import Android.support.v4.app.fragment;import Android.support.v4.app.fragmentmanager;import Android.support.v4.app.fragmenttransaction;import Android.support.v7.app.actionbaractivity;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;public class MainActivity Extends Actionbaractivity implements Fragmentcallback{private Button btn;private MyFragment1 fragment1;private MyFragment2 fragment2;private fragmentmanager fragmentmanager;private Fragment currentfragment; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_ Main); Fragmentmanager = Getsupportfragmentmanager (); Fragmenttransaction fragmenttransaction = Fragmentmanager.begintransaction (); Fragmenttransaction.setcustomanimations (Android. R.anim.fade_in, Android. R.anim.fade_out); fragment1 = new MyFragment1 (); Bundle data = new Bundle (;d ata.putstring ("TEXT", "This is the value Activiy passed through the bundle"); fragment1.setarguments (data);// Pass the value Fragmenttransaction.add (R.ID.RL_CONTAINER,FRAGMENT1) through the bundle to the activity;// Set Fragment1 to Layout fragmenttransaction.addtobackstack (null); Fragmenttransaction.commitallowingstateloss (); Currentfragment = fragment1;//initializes the button control BTN = (Button) Findviewbyid (R.ID.BTN); Btn.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {if (currentfragment instanceof MyFragment1) {switchfragment ();} else{//is currently fragment2, so you just need to fragment2 out the stack to become fragment1fragmentmanager.popbackstack (); currentfragment = Fragment1;}});} /** * Toggle Fragment */private void Switchfragment () {if (null = = Fragment2) {//can avoid toggling when re-creating Fragment2 = new MyFragment2 ();} Bundle data = new Bundle ();d ata.putstring ("TEXT", "passed to Fragment2"); fragment2.setarguments (data); Fragmenttransaction fragmenttransaction = Fragmentmanager.begintransaction (); Fragmenttransaction.setcustomanimations (Android. R.anim.fade_in, Android. R.anim.fade_out); Fragmenttransaction.aDD (R.ID.RL_CONTAINER,FRAGMENT2); Fragmenttransaction.addtobackstack (null); Fragmenttransaction.commitallowingstateloss (); currentfragment = Fragment2;} public void Changebuttoncolor () {btn.setbackgroundcolor (color.red);} @Overridepublic void CallbackFun1 (Bundle arg) {//TODO auto-generated method Stubswitchfragment ();//Toggle}@ by callback overridepublic void callbackFun2 (Bundle arg) {//TODO auto-generated method Stubchangebuttoncolor ();// Invoke method in activity by callback}}
Initial screen
After switching to the second fragment, through the Fragment2 callback, after changing the button background.
Attention:
1. It is not recommended to invoke the activity method directly in the fragment through the getactivity and then the strong transfer activity mode ! Because this will make the fragment of the compatibility worse.
Workaround: Use instanceof to determine the type of activity before use
2. Fragmenttransaction by using the Setcustomanimations method, you can add a variety of different animations to the fragment switch. The change pattern is much more than the switching animation between activity and activity.
3. Between multiple fragment, you can use the activity to reuse a lot of code, improve efficiency.
4. We can also manage fragment through Viewpager, add multiple fragment through adapter, and then switch through Setcurrentitem. We can also pass data to fragment through Setarguments.