An example of fragment and activity communication in Android application development _android

Source: Internet
Author: User
Tags gettext inheritance

First, if you want to use fragment in android3.0 and the following versions, you must quote Android-support-v4.jar this package
Then you write the activity can no longer inherit from the activity class, but to inherit Android.support.v4.app.FragmentActivity, some other parent classes also have corresponding changes.
Because fragment and activity are instantiated into two unrelated objects in the Android implementation mechanism, The connection between them is maintained by a member object of the activity Fragmentmanager. Fragment is instantiated and then goes to the fragmentmanager in the activity to register, This action is encapsulated in the Onattach of the Fragment object, so you can declare some callback interfaces in fragment and instantiate the callback interfaces when fragment calls Onattach. So fragment can invoke the member functions of each activity, of course the activity must implements these interfaces, otherwise it will be wrapped Classcasterror
Fragment and activity callback mechanism is a perfect interpretation of OOP!
Here is an example to illustrate:
First, let's look at the interface

The TextView on the left will change depending on the button on the right click.

Here's how to start the introduction code:

1. New Fragment1.xml in Layout

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
 android:layout_width=" match_parent "
 android:layout_height=" Match_parent "
 android: Background= "#00ff00"
 android:orientation= "vertical" >
 <textview
 android:id= "@+id/fragment_" Text "
 android:layout_width=" wrap_content "
 android:layout_height=" wrap_content "
 android:text=" this is fragment 1 "
 android:textcolor=" #000000 "
 android:textsize=" 25sp "/>
</LinearLayout>

As you can see, there's only one textview here.

2. New Fragment2.xml in Layout

<?xml version= "1.0" encoding= "Utf-8"?> <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:layout_width= "WRAP_" Content "
 android:layout_height=" wrap_content "
 android:text=" This is Fragment 2 "
 android:textcolor=" # 000000 "
 android:textsize=" 25sp "/>
 <button
 android:id=" @+id/button "
 android:layout_ Width= "Wrap_content"
 android:layout_height= "wrap_content"
 android:text= "num 1"/>
 <button
 android:id= "@+id/button2"
 android:layout_width= "wrap_content"
 android:layout_height= "WRAP_" Content "
 android:text=" num 2 "/>
 <button
 android:id=" @+id/button3 "
 android:layout_ Width= "Wrap_content"
 android:layout_height= "wrap_content"
 android:text= "num 3"/>
</ Linearlayout>

Here are three button

3. Create Class Fragment1 inheritance Fragment

Package lgx.fram.framents;

Import android.app.Fragment;
Import Android.os.Bundle;
Import Android.view.LayoutInflater;
Import Android.view.View;
Import Android.view.ViewGroup;

public class Fragment1 extends Fragment {
 @Override public
 View Oncreateview (layoutinflater inflater, ViewGroup Container,
  Bundle savedinstancestate) {return
 inflater.inflate (R.layout.fragment1, container, false);
 }
}

Rewrite the Oncreateview () method, where return Inflater.inflate (R.layout.fragment1, container, false); This sentence is the key

4. Create Class Fragment2 inheritance Fragment

Package lgx.fram.framents;
Import android.app.Fragment;
Import Android.os.Bundle;
Import Android.view.LayoutInflater;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.view.ViewGroup;
Import Android.widget.Button;

Import Android.widget.TextView; public class Fragment2 extends Fragment {@Override public View oncreateview (Layoutinflater inflater, ViewGroup containe
 R, Bundle savedinstancestate) {return inflater.inflate (R.layout.fragment2, container, false);
 } TextView TextView;

 Button button, button2, Button3;
 @Override public void onactivitycreated (Bundle savedinstancestate) {super.onactivitycreated (savedinstancestate);
 Button = (button) getactivity (). Findviewbyid (R.id.button);
 Button2 = (Button) getactivity (). Findviewbyid (R.id.button2);
 Button3 = (Button) getactivity (). Findviewbyid (R.id.button3);
 TextView = (TextView) getactivity (). Findviewbyid (R.id.fragment_text); Button.setonclicklistener (New Onclicklistener () {@Override Public void OnClick (View v) {textview.settext (Button.gettext ());
 }
 }); Button2.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {Textview.settext (button2
  . GetText ());
 }
 }); Button3.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {Textview.settext (Button3
  . GetText ());
 }
 }); 
 } button = (button) getactivity (). Findviewbyid (R.id.button);

This method is used to get the control above the fragment

The code inside the 5.activity_fragment.xml is like this.

<?xml version= "1.0" encoding= "Utf-8"?> <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:baselinealigned= "false"
 android:orientation= "Horizontal" >
 < Fragment
 android:id= "@+id/fragment1"
 android:name= "Lgx.fram.framents.Fragment1"
 android:layout_ Width= "Match_parent"
 android:layout_height= "match_parent"
 android:layout_weight= "1"/>
 < Fragment
 android:id= "@+id/fragment2"
 android:name= "Lgx.fram.framents.Fragment2"
 android:layout_ Width= "Match_parent"
 android:layout_height= "match_parent"
 android:layout_weight= "1"/>
</ Linearlayout>

Note: The android:name= in the control fragment "" is filled with the absolute path of your fragment class (the brain suddenly shorted out, is this said??) ), the ID is used to mark fragment.

6.FragmentActivity is the simplest, just setcontentview, and no other changes have been made. Look underneath.

Package lgx.fram.framents;

Import android.app.Activity;
Import Android.os.Bundle;


public class Fragmentactivity extends activity {

 @Override
 protected void onCreate (Bundle savedinstancestate) {
 super.oncreate (savedinstancestate);
 Setcontentview (r.layout.activity_fragment);
 }



Here my whole little application is done. My fragment is added to the activity through the layout file, and another way is to add fragment to the activity programmatically. Here I'm simply describing

None of the above 1,2,3,4 need to move.

5th step, the code inside the activity_fragment.xml becomes the following

<?xml version= "1.0" encoding= "Utf-8"?> <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:baselinealigned= "false"
 android:orientation= "Horizontal" >
< /linearlayout>

You will find my knowledge removed two fragment, the whole linearlayout added ID

The 6th step, the annotation inside, has been written very clearly:

Package lgx.fram.framents;

Import Android.os.Bundle;
Import android.app.Activity;
Import Android.view.Display;
Import Android.view.Menu;

@author Lenovo Dynamic Add fragment is mainly divided into 4 steps:
(1) obtain to Fragmentmanager, in the activity can be obtained directly through Getfragmentmanager.
(2) Open a transaction by invoking the BeginTransaction method.
(3) Adding fragment to the container, typically using the Replace method, requires the ID of the incoming container and an instance of fragment.
(4) Commit the transaction and invoke the Commit method.

public class Fragmentactivity extends activity {

 @Override
 protected void onCreate (Bundle savedinstancestate) {
 super.oncreate (savedinstancestate);
 Setcontentview (r.layout.activity_fragment);
 Display display = Getwindowmanager (). Getdefaultdisplay ();
 if (Display.getwidth () > Display.getheight ()) {
  Fragment1 fragment1 = new Fragment1 ();
  Getfragmentmanager (). BeginTransaction ().
   Replace (r.id.main_layout, fragment1). commit ();
 } else {
  Fragment2 Fragment2 = new Fragment2 ();
  Getfragmentmanager (). BeginTransaction ().
   Replace (r.id.main_layout, Fragment2). commit ();
 }
 }



This code means that the horizontal screen displays different fragment. If it is a simulator test, press CTRL+F11.

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.