The interaction between fragment and activity in Android (two ways to implement) _android

Source: Internet
Author: User
Tags commit set background

(Fragment layout is not set backgound)

Before about the concept of fragment in Android and how to create it, I wrote a blog post, "Explain the two ways to create Android fragment," and make a detailed analysis of how to create a fragment hybrid layout. Let's go into detail today about how fragment interacts with host activity.

We can understand that in the host activity to achieve information interaction between the fragment, it must be through the host activity,fragment between the direct implementation of information interaction.

Fragment and fragment or the data interaction with the activity (deploying part of fragment's layout directly in the activity) I have summed up two ways to achieve this:

(1) through bundle, so as to realize the data interaction between fragment

(2) by defining a callback interface within the fragment and requiring the host activity to implement it. When an activity receives a callback through an interface, it can share information, if necessary, with other fagment in the layout.

Before you start the two implementations, introduce and demonstrate some of the effects of the different settings of the personalization parameters, before introducing the fragment to manage the host activity, you must get Fragmentmanager (fragmentation management), and Fragmentmanager to achieve fragment additions and deletions and other operations (transactions), you must enable fragmenttransaction, here mainly to show you add Fragmenttransaction.addtobackstack method before and after the fragment is set background In the case of using the different effects of fragmenttransaction.add and replace, more detailed method introduction and usage please refer to the API for detailed understanding.

The Fragmenttransaction.addtobackstack method demo effect is not set (when multiple layers are turned on, the fallback is withdrawn and the program is exited directly):

Set the Fragmenttransaction.addtobackstack method demo effect (there is no listener that listens for background stack changes to judge processing):

Seemingly do not see the difference, in fact, in the Back button, this is in accordance with the order of open, one exit

Use Fragmenttransaction.add's demo effect without setting background on fragment:

Note that the emphasis here is not to the right fragment layout settings backgound situation, if the set of backgound, then the implementation effect and replace no difference, which is the main reason for the timeout today so much

Different implementations we've seen, we're starting to demonstrate implementation code:

We are using the layout files of the fragment in Android (which add fragment to host activity through Java code), and the layout file code refer to http://www.cnblogs.com/panhouye/ P/6185093.html

(1) Pass bundle

The first step: the right fragment corresponding Java code Rightfragment.java:

Import android.app.Fragment;
Import Android.os.Bundle;
Import Android.view.LayoutInflater;
Import Android.view.View;
Import Android.view.ViewGroup;
Import Android.widget.TextView;
 /** * Created by Panchengjia on 2016/12/18. * * public class Rightfragment extends Fragment {public rightfragment () {}/*fragment's pass-through (passed by bundle object) * Using this method of reference can Ensure that the parameters passed by the user on the screen switch are not lost/public static rightfragment getinstance (String data) {rightfragment rightfragment = new R
 Ightfragment ();
 Bundle Bundle = new Bundle ();
 The string to be passed is passed into the bundle bundle.putstring ("data", data) in the form of a key-value pair;
 Rightfragment.setarguments (bundle);
 return rightfragment;
 @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); @Override public View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {View VI
 EW =inflater.inflate (R.LAYOUT.RIGHT_LAYOUT,CONTAINER,FALSE);
 TextView TV = (TextView) View.findviewbyid (r.id.tv); String data = Getarguments (). getString ("Data");
 Tv.settext (data);
 return view;
 @Override public void OnPause () {super.onpause (); }
}

Step Two: the Java implementation code for the primary layout host activity Mainactivity.java:

Import Android.app.FragmentManager;
Import android.app.FragmentTransaction;
Import android.support.v7.app.AppCompatActivity;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.widget.Button;
 public class Main3activity extends appcompatactivity {Fragmentmanager fragmentmanager;
 Fragmenttransaction fragmenttransaction;
 Leftfragment leftfragment; Button panhouye,bikonghai;//declare the buttons in leftfragment @Override protected void onCreate (Bundle savedinstancestate) {Super.on
 Create (savedinstancestate);
 Setcontentview (r.layout.activity_main2);
 Obtain Fragmentmanager Fragmentmanager=getfragmentmanager ();
 Find Leftfragment leftfragment = (leftfragment) Fragmentmanager.findfragmentbyid (R.id.left) through Findfragmentbyid;
 Locate the corresponding navigation button and set the Click event Panhouye = (Button) Leftfragment.getview (). Findviewbyid (R.id.panhouye);
 Bikonghai = (Button) Leftfragment.getview (). Findviewbyid (R.id.bikonghai); Panhouye.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {
  Invokes the method to modify the textual content in the Rightfragment Switchbutton ("I am Mr. Pan Ye");
 }
 }); Bikonghai.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {Switchbutton ("I am Azure
  Sea ");
 }
 });
 Sets the default text content in Rightfragment after an activity is opened Switchbutton ("I Am pan ye"); The//defined method fills the fragment on the right side of the activity and modifies the text content by passing parameters public void Switchbutton (String data) {Fragmentmanager=getfragmentmanager (
 );
 Fragmenttransaction=fragmentmanager.begintransaction ();
 Modify Text rightfragment rightfragment =rightfragment.getinstance (data) by calling the GetInstance method in Rightfragment;
 Using the Add method at this point causes the right fragment to overlap (background) fragmenttransaction.replace (r.id.right,rightfragment);
 Fragmenttransaction.commit (); }
}

(2) interface callback

The first step: the Left Fragment Java implementation code Leftfragment.java file

This demo uses the button in the left fragment to trigger the interaction with the right fragment data, so you need to add a callback interface in this class to callback the method that modifies the right text in the host activity.

Import android.app.Fragment;
Import Android.os.Bundle;
Import Android.view.LayoutInflater;
Import Android.view.View;
Import Android.view.ViewGroup;
Import Android.widget.Button;
 /** * Created by Panchengjia on 2016/12/18. */public class Leftfragment extends Fragment implements view.onclicklistener{//declaration internally defined callback interface Callbacklistener Callbackli
 Stener;
 Declare the Event Trigger button Panhouye,bikonghai in the layout;
 @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
 Gets the interface callbacklistener= (Callbacklistener) getactivity () for the callback modification text method by Getactivity (). @Override public View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {View VI
 EW =inflater.inflate (R.LAYOUT.LEFT_LAYOUT,CONTAINER,FALSE);
 Panhouye = (Button) View.findviewbyid (R.id.panhouye);
 Bikonghai= (Button) View.findviewbyid (R.id.bikonghai);
 Panhouye.setonclicklistener (this)//set the Listener event for the button Bikonghai.setonclicklistener (this);
 return view; @Override Public VOID OnPause () {super.onpause (); @Override public void OnClick (View v) {switch (V.getid ()) {Case R.id.panhouye:callbacklistener.settext ("I Am Prince Pan")
  ;
  Break
  Case R.id.bikonghai:callbacklistener.settext ("I Am the Azure Sea");
 Break
 }//Set the callback interface for modifying the text public static interface callbacklistener{public void SetText (String data);
 }
}

Step two: The right fragment Java implementation code Rightfragment.java file

This demo to the right for the text display fragment, but also click on the left button, by changing the form of text to reflect the click of the event processing, so you must add the method of text modification in this fragment class.

 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;
Import Android.widget.TextView;
 /** * Created by Panchengjia on 2016/12/18.
 * * public class Rightfragment extends Fragment {//Declaration Fragment TextView, used to establish the method of modifying text private TextView TV;
 @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
 @Override public void OnPause () {super.onpause ();  @Nullable @Override public View oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate)
 {View View =inflater.inflate (R.layout.right_layout,container,false);
 TV = (TextView) View.findviewbyid (r.id.tv);
 return view;
 The method for modifying its own text is set here///This is public void Setfragmenttext (String data) {tv.settext (data); }
}

Step three: acvtivity Java implementation Code Mainactivity.java file for the main interface host (to receive the fragment event callback, the host's activity must implement the callback interface):

Import Android.app.FragmentManager;
Import android.app.FragmentTransaction;
Import android.support.v7.app.AppCompatActivity;
Import Android.os.Bundle; public class Mainactivity extends appcompatactivity implements leftfragment.callbacklistener{Fragmentmanager
 Fragmentmanager;
 Fragmenttransaction fragmenttransaction;
 /*leftfragment has been declared in the master layout file, * This only needs to be deployed through the code declaration rightfragment/Rightfragment Rightfragment;
 @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
 Setcontentview (R.layout.activity_main);
 Initialize main layout (main purpose is to populate fragments) initactivity ();
 private void Initactivity () {Fragmentmanager = Getfragmentmanager ();
 Fragmenttransaction = Fragmentmanager.begintransaction ();
 Rightfragment = new Rightfragment ();
 Fragmenttransaction.add (r.id.right,rightfragment);
 Fragmenttransaction.commit (); }//Interface implementation method, used to callback the method of modifying text defined in the Rightfragment class @Override public void SetText (String data) {Rightfragment.setfragmenttext (da
 TA); }
}

Summary:

This demo interface callback is implemented in a way that looks a bit larger than the code that uses bundle, but in actual development, the fragment we face is not just these two, but using interface callbacks to implement interactive data is a better way to reuse fragment UI components, Fundamentally solve the problem of a large number of code reuse, we recommend that you master the interface callback to achieve data interaction.

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, but also hope that a lot of support cloud Habitat community!

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.