Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Android Fragment really fully resolve     - C ++ two second pointer memory model (two-dimensional array) (Programming)

- Httpclient4.4 of principle (Http execution context) (Programming)

- Oracle 10g New Features - Archive Compression (Database)

- Android Custom View password box example (Programming)

- MySQL Authorized a recovered (Database)

- CentOS / Linux restart active NIC connection paths / network configure error Error Resolution (Linux)

- Understanding Java classes (Programming)

- Linux systems use logwatch log file monitoring (Linux)

- Install FFmpeg compiling from source in Mac OS X environment (Linux)

- String JavaScript type system (Programming)

- Open MySQL slow query log (Database)

- Explore Android SQLite3 multithreading (Programming)

- Moosefs Distributed File System Configuration (Server)

- Linux prohibit non-WHEEL user su command Detail (Linux)

- Source compiler install Nginx (Server)

- Radius server setup under CentOS (Server)

- C language print various graphic (Programming)

- Android first line of code study notes (Programming)

- Linux SVN account password to save your settings (Linux)

- The oh-my-zsh into true my zsh (Linux)

 
         
  Android Fragment really fully resolve
     
  Add Date : 2018-11-21      
         
         
         
  Since Fragment appeared, there was a time, I feel able to talk about what we talk about relations with Fragment, should be asked what to do next Fragment can not achieve ~ ~ ~ Haha, is not it a bit too ~~~

This blog seeks to explain Fragment how we produce, what is Fragment, Fragment life cycle, how to use static and dynamic Fragment, Fragment fallback stack, Fragment affairs; as well as some special purpose Fragment, such as: What is not Fragment Layout usefulness? Fragment how to interact with the Activity? Fragment how to create dialog? Fragment how to integrate with ActionBar and so on.

1, Fragment generation and presentation

Android running on a variety of devices, small screens of mobile phones, flat-panel large-screen TV even. Screen size for the gap, in many cases, are the first to develop a mobile phone for the App, then copy, modify the layout to accommodate the tablet Shenma super large screen. Do not do a App can adapt to mobile phones and tablet Why, of course, there must be ah. Fragment emergence is to solve this problem. You can Fragment as an integral part of an interface Activity even Activity interface can be completely different Fragment composition, more handsome it is Fragment has its own life cycle and receiving, handling user events, so you do not Activity write a bunch of event handling code control. More importantly, you can dynamically add, remove and replace a Fragment.

2, Fragment life cycle

Fragment must be interdependent and Activity exist, thus Activity life cycle will directly affect the Fragment life cycle.

We can see more than a few extra Fragment lifecycle callbacks ratio Activity:
onAttach (Activity)
Called when Fragment occurrence associated with the Activity.
onCreateView (LayoutInflater, ViewGroup, Bundle)
Creating the Fragment of view
onActivityCreated (Bundle)
When the Activity onCreate method call to return
onDestoryView ()
OnCreateView want to cope with, the call when the Fragment view removed
onDetach ()
And onAttach Correspondingly, when Fragment Activity associated with the call is canceled
Note: In addition onCreateView, all other methods if you rewrite, you must call the parent class for the implementation of the method,

3, static use Fragment

Hey, finally time to use the ~

This is done using Fragment easiest way to Fragment as normal controls, directly written in the Activity of the layout file. step:

1, inheritance Fragment, rewrite onCreateView decided Fragemnt layout

2, in a statement this Fragment Activity in just the same as ordinary View

An example is shown below (I used 2 Fragment as Activity layout, a Fragment layout for the title, a Fragment for content layout):

TitleFragment layout file:


< ? 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 = "45dp"
    android: background = "@ drawable / title_bar">

    < ImageButton
        android: id = "@ + id / id_title_left_btn"
        android: layout_width = "wrap_content"
        android: layout_height = "wrap_content"
        android: layout_centerVertical = "true"
        android: layout_marginLeft = "3dp"
        android: background = "@ drawable / showleft_selector" />

    < TextView
        android: layout_width = "fill_parent"
        android: layout_height = "fill_parent"
        android: gravity = "center"
        android: text = "I'm not micro-letters"
        android: textColor = "# fff"
        android: textSize = "20sp"
        android: textStyle = "bold" />

< / RelativeLayout>

TitleFragment

package com.zhy.zhy_fragments;

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.ImageButton;
import android.widget.Toast;

public class TitleFragment extends Fragment
{

private ImageButton mLeftMenu;

@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate (R.layout.fragment_title, container, false);
mLeftMenu = (ImageButton) view.findViewById (R.id.id_title_left_btn);
mLeftMenu.setOnClickListener (new OnClickListener ()
{
@Override
public void onClick (View v)
{
Toast.makeText (getActivity (),
"I am an ImageButton in TitleFragment!",
Toast.LENGTH_SHORT) .show ();
}
});
return view;
}
}

Similarly there ContentFragment its layout file:

 
< ? 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: orientation = "vertical">

    < TextView
        android: layout_width = "fill_parent"
        android: layout_height = "fill_parent"
        android: gravity = "center"
        android: text = "call the shots using Fragment Panel"
        android: textSize = "20sp"
        android: textStyle = "bold" />

< / LinearLayout>
 

package com.zhy.zhy_fragments;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class ContentFragment extends Fragment
{

@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate (R.layout.fragment_content, container, false);
}

}

MainActivity

 
package com.zhy.zhy_fragments;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;

public class MainActivity extends Activity
{

@Override
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate (savedInstanceState);
requestWindowFeature (Window.FEATURE_NO_TITLE);
setContentView (R.layout.activity_main);
}

}

Activity's layout file:

 
< 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">

    < Fragment
        android: id = "@ + id / id_fragment_title"
        android: name = "com.zhy.zhy_fragments.TitleFragment"
        android: layout_width = "fill_parent"
        android: layout_height = "45dp" />

    < Fragment
        android: layout_below = "@ id / id_fragment_title"
        android: id = "@ + id / id_fragment_content"
        android: name = "com.zhy.zhy_fragments.ContentFragment"
        android: layout_width = "fill_parent"
        android: layout_height = "fill_parent" />

< / RelativeLayout>

The Fragment is not as common as declared in the Activity View layout file and event handling code for all controls by the respective Fragment to deal with, and instantly feel Activity good clean and there are wood ~ ~ readability of code, complex usability and maintainability is not an instant upgrade the ~~~

4, dynamic use of Fragment

As already demonstrated, the easiest way to use Fragment ~ Here's how to dynamically add, update, and delete Fragment

In order to use dynamic Fragment, we modify Actvity layout file, use a middle FrameLayout, add the following four buttons Hey ~ ~ ~ ~ ~ is not a micro-channel button - -!

< 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">

    < Fragment
        android: id = "@ + id / id_fragment_title"
        android: name = "com.zhy.zhy_fragments.TitleFragment"
        android: layout_width = "fill_parent"
        android: layout_height = "45dp" />

    < Include
        android: id = "@ + id / id_ly_bottombar"
        android: layout_width = "fill_parent"
        android: layout_height = "55dp"
        android: layout_alignParentBottom = "true"
        layout = "@ layout / bottombar" />

    < FrameLayout
        android: id = "@ + id / id_content"
        android: layout_width = "fill_parent"
        android: layout_height = "fill_parent"
        android: layout_above = "@ id / id_ly_bottombar"
        android: layout_below = "@ id / id_fragment_title" />

< / RelativeLayout>

Four buttons at the bottom of the layout is not posted, to see renderings when will understand ~~

Below the main Activity

package com.zhy.zhy_fragments;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.LinearLayout;

public class MainActivity extends Activity implements OnClickListener
{
private LinearLayout mTabWeixin;
private LinearLayout mTabFriend;

private ContentFragment mWeixin;
private FriendFragment mFriend;

@Override
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate (savedInstanceState);
requestWindowFeature (Window.FEATURE_NO_TITLE);
setContentView (R.layout.activity_main);

// Declare and initialize control events
mTabWeixin = (LinearLayout) findViewById (R.id.tab_bottom_weixin);
mTabFriend = (LinearLayout) findViewById (R.id.tab_bottom_friend);
mTabWeixin.setOnClickListener (this);
mTabFriend.setOnClickListener (this);

// Set the default Fragment
setDefaultFragment ();
}

private void setDefaultFragment ()
{
FragmentManager fm = getFragmentManager ();
FragmentTransaction transaction = fm.beginTransaction ();
mWeixin = new ContentFragment ();
transaction.replace (R.id.id_content, mWeixin);
transaction.commit ();
}

@Override
public void onClick (View v)
{
FragmentManager fm = getFragmentManager ();
// Open Fragment Affairs
FragmentTransaction transaction = fm.beginTransaction ();

switch (v.getId ())
{
case R.id.tab_bottom_weixin:
if (mWeixin == null)
{
mWeixin = new ContentFragment ();
}
// Fragment of the current layout of the controls alternative id_content
transaction.replace (R.id.id_content, mWeixin);
break;
case R.id.tab_bottom_friend:
if (mFriend == null)
{
mFriend = new FriendFragment ();
}
transaction.replace (R.id.id_content, mFriend);
break;
}
// Transaction.addToBackStack ();
// Transaction commit
transaction.commit ();
}

}

You can see that we use FragmentManager Fragment of the dynamic load, the method used here is to replace ~ ~ next section I will detail the common API FragmentManager.

NOTE: If you use the following version Android3.0, need to introduce v4 package, then Activity inheritance FragmentActivity, then get FragmentManager by getSupportFragmentManager. However, it is recommended that version Menifest file uses-sdk instead of minSdkVersion and targetSdkVersion are 11 or more, so you do not have to introduce v4 package.

There are two intermediate code is a subclass of Fragment, ContentFragment have seen above, FriendFragment in fact, something like:

package com.zhy.zhy_fragments;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FriendFragment extends Fragment
{

@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate (R.layout.fragment_friend, container, false);
}

}

Can be seen to achieve a good effect, in fact, the effect of previous blog also appeared in the blog: Android Tab type project summarizes the main interface Large Fragment + TabPageIndicator + ViewPager, we are interested can look. ps: For brevity code, do not click on the Change button to add what the main explanations for the ~~~

5, Fragment family common API

Fragment usual three categories:

android.app.Fragment mainly used to define Fragment

android.app.FragmentManager mainly used in operating Fragment Activity

android.app.FragmentTransaction guarantee atomic operations of some columns Fragment familiar with the transaction term, you will be able to understand -

a, get FragmentManage way:

getFragmentManager () // v4 in, getSupportFragmentManager

b, the main operations are FragmentTransaction method

FragmentTransaction transaction = fm.benginTransatcion (); // start a transaction

transaction.add ()

Activity in to add a Fragment

transaction.remove ()

Remove from Activity of a Fragment, Fragment removed if not added to the fallback stack (the stack will be rolled back later in detail), the Fragment instances will be destroyed.

transaction.replace ()

Use another Fragment replace the current actually remove () and add () fit ~

transaction.hide ()

Hide current Fragment, just to invisible, and does not destroy

transaction.show ()

Before the Show hidden Fragment

detach ()

View will be removed from the UI, and remove () different, this time the state is still maintained by the fragment FragmentManager.

attach ()

Reconstruction view view, attached to the UI and display.

transatcion.commit () // commit a transaction

NOTE: Standard Fragment buddies, you may often encounter such inconsistent Activity Status: This error State loss. Mainly due to: commit method must call Activity.onSaveInstance (before).

Above, substantially all manner Fragment of, and in turn to submit a transaction can be carried out multiple add, remove, replace and other operations.

It is worth noting: If you prefer to use Fragment, must be aware of these methods, which will destroy the view, which will destroy the instance, which is just hidden, so as to better use them.

a, for example: I FragmentA the EditText fill some data when switching to FragmentB, if you want to see the data also will go to A, then for you is to hide and show; that is, want to retain the user's operation panel, you can use the hide and show, of course not hard at that new instance, the next non-null judgment.

b, another example: I do not want to keep the user operation, you can use the remove (), and then add (); or use the replace () This and remove, add the same effect.

c, remove and detach a little subtle differences, without considering the fallback stack case, remove the entire Fragment instances will be destroyed, and detach it just destroy their view of the structure, the instance will not be destroyed. Both choose how to use it? If your current Activity has always existed, so when you do not want to retain user operation, you can use the priority detach.

 

Has completed the above described methods Fragment common, I believe after reading, we must clear produce Fragment grounds, as well as how to use the Fragment, again according to the API to explain, but also to understand why once felt Fragment column will be some chaos seventy-eight problems groove, after all, is not clear because of its life-cycle.

Due to space reasons, the remaining contents of the left to the next. In the next, it will be introduced:

1, how to manage Fragment fallback stack

2, Fragment how to interact with Activity

3, best practices Fragment interacting with Activity

4, no view of the usefulness of Fragment

5, using the Create Fragment dialog box

6, how to integrate with ActionBar, MenuItem, etc. ~ ~

Part blog has been introduced in the Fragment causes, as well as some basic usage and various API.

This article deals presentation on the blog post mentioned: how to manage the fallback stack Fragment, Fragment how Activity interact, Fragment Activity and interact with the best practice, there is no view of the usefulness of Fragment, Fragment use to create the dialog box, and ActionBar, MenuItem integration ~~

1. Management Fragment fallback stack

Similar to the Android system Activity maintains a task stack, we can maintain a fallback stack to save changes each Fragment transactions that occur through the Activity. If you add the Fragment task to rollback the stack, when the user clicks the back button, you will see the last saved Fragment. Once Fragment fully ejected from the back stack, the user again clicks the back button to exit the current Activity.

Click on the first button, switch to the second screen, click the second button to switch to the third screen, and then click the Back button to turn back. This is not like a beginner Android Activity jump when, of course, certainly not here, or I'll kneel. Here is Fragment implemented, the user clicks Back, actually Fragment fallback stack constantly popped.

How to add a Fragment transaction to roll back the stack:

FragmentTransaction.addToBackStack (String)

Here to explain the code: Obviously a total of three and a Fragment Activity.

Look at the Activity's layout file:

< 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">

    < FrameLayout
        android: id = "@ + id / id_content"
        android: layout_width = "fill_parent"
        android: layout_height = "fill_parent">
    < / FrameLayout>

< / RelativeLayout>

Different Fragment displayed in this FrameLayout in.

MainActivity.java

package com.zhy.zhy_fragments;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Window;

public class MainActivity extends Activity
{


 @Override
 protected void onCreate (Bundle savedInstanceState)
 {
  super.onCreate (savedInstanceState);
  requestWindowFeature (Window.FEATURE_NO_TITLE);
  setContentView (R.layout.activity_main);

  FragmentManager fm = getFragmentManager ();
  FragmentTransaction tx = fm.beginTransaction ();
  tx.add (R.id.id_content, new FragmentOne (), "ONE");
  tx.commit ();
 }

}

Very simple, direct FragmentOne add to the layout file FrameLayout, pay attention here and did not call FragmentTransaction.addToBackStack (String), because I do not like the current display, click the Back button appears white. But the correct corresponding Back key to exit our Activity.

Here is FragmentOne

package com.zhy.zhy_fragments;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
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;

public class FragmentOne extends Fragment implements OnClickListener
{

 private Button mBtn;

 @Override
 public View onCreateView (LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState)
 {
  View view = inflater.inflate (R.layout.fragment_one, container, false);
  mBtn = (Button) view.findViewById (R.id.id_fragment_one_btn);
  mBtn.setOnClickListener (this);
  return view;
 }

 @Override
 public void onClick (View v)
 {
  FragmentTwo fTwo = new FragmentTwo ();
  FragmentManager fm = getFragmentManager ();
  FragmentTransaction tx = fm.beginTransaction ();
  tx.replace (R.id.id_content, fTwo, "TWO");
  tx.addToBackStack (null);
  tx.commit ();

 }

}

We FragmentOne click the button, use the replace method, if you read a blog before, we must remember to replace the add remove and fit, and if you do not add the transaction to roll back the stack, before a Fragment instance will be destroyed . Here it is clear that we call tx.addToBackStack (null); add the current transaction to roll back the stack, so FragmentOne instance will not be destroyed, but the view hierarchy will still be destroyed, that calls onDestoryView and onCreateView, evidence that: careful see above renderings, before we jump in the contents of the text input box, the user interface Back to get the first time gone.

Next FragmentTwo

package com.zhy.zhy_fragments;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
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;

public class FragmentTwo extends Fragment implements OnClickListener
{

 private Button mBtn;
 @Override
 public View onCreateView (LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState)
 {
  View view = inflater.inflate (R.layout.fragment_two, container, false);
  mBtn = (Button) view.findViewById (R.id.id_fragment_two_btn);
  mBtn.setOnClickListener (this);
  return view;
 }
 @Override
 public void onClick (View v)
 {
  FragmentThree fThree = new FragmentThree ();
  FragmentManager fm = getFragmentManager ();
  FragmentTransaction tx = fm.beginTransaction ();
  tx.hide (this);
  tx.add (R.id.id_content, fThree, "THREE");
// Tx.replace (R.id.id_content, fThree, "THREE");
  tx.addToBackStack (null);
  tx.commit ();
 }


}

Click here, we did not use replace, but to hide the current Fragment, and then add the FragmentThree instance, and finally add the transaction to roll back the stack. The aim is to provide a solution for everyone: If you do not want the view to redraw the how to do, please look carefully again renderings, we FragmentTwo content of EditText filled, user Back back when the data is still ~~~

Finally FragmentThree is a simple Toast:

package com.zhy.zhy_fragments;

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.Toast;

public class FragmentThree extends Fragment implements OnClickListener
{

 private Button mBtn;

 @Override
 public View onCreateView (LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState)
 {
  View view = inflater.inflate (R.layout.fragment_three, container, false);
  mBtn = (Button) view.findViewById (R.id.id_fragment_three_btn);
  mBtn.setOnClickListener (this);
  return view;
 }

 @Override
 public void onClick (View v)
 {
  Toast.makeText (getActivity (), "i am a btn in Fragment three",
    Toast.LENGTH_SHORT) .show ();
 }

}

Well, after the above description, you should already know how Fragment fallback stack is a different story, as well as their application scenarios hide, replace, etc.

Here extremely note: The above code does not have any reference to the overall value, solely in order to show the stack after the rollback, in communication with the later explained Fragment Activity, reconstructs the code above!

2, Fragment communicate with Activity

Because all of Fragment Activity is attached, so communication is not so complicated, probably summarized as follows:

a, if you Activity contains its own management Fragment of reference, you can access all the public methods Fragment directly by reference

b, if not save any Fragment Activity references, so it does not matter, each has a unique Fragment TAG or ID, you can getFragmentManager.findFragmentByTag () or findFragmentById () to obtain any Fragment instance, and then to operate.

c, can be obtained in the current instance Fragment Binding Activity by getActivity, then operate.

NOTE: If you need Fragment Context, by calling getActivity (), if there needs to be destroyed in the Context Activity, using getActivity () getApplicationContext ()..

3, best practices and communication Fragment of Activity

For reasons of reusable Fragment, it is necessary to reduce the coupling Fragment and Activity, and we should not directly operate Fragment Fragment else, after all, should be operating by its Fragment Activity manager to decide.

Now I through the code in two ways, namely reconstruction, FragmentOne and FragmentTwo click event, and in response to the click event Activity:

First look FragmentOne

package com.zhy.zhy_fragments;

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;

public class FragmentOne extends Fragment implements OnClickListener
{
 private Button mBtn;

 / **
  * Click on the Settings button callback
  *
  * /
 public interface FOneBtnClickListener
 {
  void onFOneBtnClick ();
 }

 @Override
 public View onCreateView (LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState)
 {
  View view = inflater.inflate (R.layout.fragment_one, container, false);
  mBtn = (Button) view.findViewById (R.id.id_fragment_one_btn);
  mBtn.setOnClickListener (this);
  return view;
 }

 / **
  * Activity to host processing, if it wishes to deal with
  * /
 @Override
 public void onClick (View v)
 {
  if (getActivity () instanceof FOneBtnClickListener)
  {
   ((FOneBtnClickListener) getActivity ()) onFOneBtnClick ().;
  }
 }

}

You can see that the FragmentOne not coupled with any Activity Any Activity can be used; and we declare an interface to its click event callback, you want to manage its click event Activity implements this interface will be. We can see that in the first judges of the current onClick Binding Activity whether to implement this interface, if you implement the call.

Look FragmentTwo

package com.zhy.zhy_fragments;

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;

public class FragmentTwo extends Fragment implements OnClickListener
{

 
 private Button mBtn;
 
 private FTwoBtnClickListener fTwoBtnClickListener;
 
 public interface FTwoBtnClickListener
 {
  void onFTwoBtnClick ();
 }
 // Set callback interface
 public void setfTwoBtnClickListener (FTwoBtnClickListener fTwoBtnClickListener)
 {
  this.fTwoBtnClickListener = fTwoBtnClickListener;
 }
 @Override
 public View onCreateView (LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState)
 {
  View view = inflater.inflate (R.layout.fragment_two, container, false);
  mBtn = (Button) view.findViewById (R.id.id_fragment_two_btn);
  mBtn.setOnClickListener (this);
  return view;
 }
 @Override
 public void onClick (View v)
 {
  if (fTwoBtnClickListener! = null)
  {
   fTwoBtnClickListener.onFTwoBtnClick ();
  }
 }

}

Very similar FragmentOne, but we provide such a method setListener, means Activity not only implement the interface, it must also show the call mFTwo.setfTwoBtnClickListener (this).

Finally look Activity:

package com.zhy.zhy_fragments;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Window;

import com.zhy.zhy_fragments.FragmentOne.FOneBtnClickListener;
import com.zhy.zhy_fragments.FragmentTwo.FTwoBtnClickListener;

public class MainActivity extends Activity implements FOneBtnClickListener,
  FTwoBtnClickListener
{

 private FragmentOne mFOne;
 private FragmentTwo mFTwo;
 private FragmentThree mFThree;

 @Override
 protected void onCreate (Bundle savedInstanceState)
 {
  super.onCreate (savedInstanceState);
  requestWindowFeature (Window.FEATURE_NO_TITLE);
  setContentView (R.layout.activity_main);

  mFOne = new FragmentOne ();
  FragmentManager fm = getFragmentManager ();
  FragmentTransaction tx = fm.beginTransaction ();
  tx.add (R.id.id_content, mFOne, "ONE");
  tx.commit ();
 }

 / **
  * Click the button when the callback FragmentOne
  * /
 @Override
 public void onFOneBtnClick ()
 {

  if (mFTwo == null)
  {
   mFTwo = new FragmentTwo ();
   mFTwo.setfTwoBtnClickListener (this);
  }
  FragmentManager fm = getFragmentManager ();
  FragmentTransaction tx = fm.beginTransaction ();
  tx.replace (R.id.id_content, mFTwo, "TWO");
  tx.addToBackStack (null);
  tx.commit ();
 }

 / **
  * Click the button when the callback FragmentTwo
  * /
 @Override
 public void onFTwoBtnClick ()
 {
  if (mFThree == null)
  {
   mFThree = new FragmentThree ();

  }
  FragmentManager fm = getFragmentManager ();
  FragmentTransaction tx = fm.beginTransaction ();
  tx.hide (mFTwo);
  tx.add (R.id.id_content, mFThree, "THREE");
  // Tx.replace (R.id.id_content, fThree, "THREE");
  tx.addToBackStack (null);
  tx.commit ();
 }

}

Code refactoring ends with the start of exactly the same effect. The above two kinds of communication are recommended, just select one of your favorite. Click here mention: Although Fragment and Activity by getActivity with findFragmentByTag or findFragmentById, any operation, even in Fragment Fragment operation inside another, but there is no special reason is definitely not discouraged. Activity is served between Fragment similar role as the bus, you should decide how to operate by its Fragment. And while Fragment can not respond Intent open, but can Activity, Activity Intent can receive, and then displays the parameters according to which Fragment judgment.

4, how to deal with configuration changes to run

Run-time configuration changes, the most common is to rotate the screen if you do not know how to handle screen changes can refer to: Android screen rotation process and ProgressDialog the best AsyncTask http://www.linuxidc.com/Linux/2015- 08 / 121312.htm

Here mention: Many people feel forced to set the screen orientation can be, but one thing, when your application is as to the background (such as the user clicks on the home), a long time did not return, your application will be restarted . For example, the above example: If you take the example above you As FragmentThree interface, then the state is in the background, you will find that after a long time when you're home again through the opening, and above FragmentThree FragmentOne added together, this is because you restart Activity in the original FragmentThree has drawn a FragmentOne.

Well, look at the following piece of code:

Activity:

package com.zhy.zhy_fragments;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Window;

public class MainActivity extends Activity

{
 private FragmentOne mFOne;

 @Override
 protected void onCreate (Bundle savedInstanceState)
 {
  super.onCreate (savedInstanceState);
  requestWindowFeature (Window.FEATURE_NO_TITLE);
  setContentView (R.layout.activity_main);

  mFOne = new FragmentOne ();
  FragmentManager fm = getFragmentManager ();
  FragmentTransaction tx = fm.beginTransaction ();
  tx.add (R.id.id_content, mFOne, "ONE");
  tx.commit ();

 }

}

Fragment

package com.zhy.zhy_fragments;

import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragmentOne extends Fragment
{
 private static final String TAG = "FragmentOne";

 @Override
 public View onCreateView (LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState)
 {
  Log.e (TAG, "onCreateView");
  View view = inflater.inflate (R.layout.fragment_one, container, false);
  return view;
 }

 @Override
 public void onCreate (Bundle savedInstanceState)
 {
  // TODO Auto-generated method stub
  super.onCreate (savedInstanceState);

  Log.e (TAG, "onCreate");
 }

 @Override
 public void onDestroyView ()
 {
  // TODO Auto-generated method stub
  super.onDestroyView ();
  Log.e (TAG, "onDestroyView");
 }

 @Override
 public void onDestroy ()
 {
  // TODO Auto-generated method stub
  super.onDestroy ();
  Log.e (TAG, "onDestroy");
 }

}

The code is very simple, when you run, constantly rotating screen, you will find that each rotation of the screen, the screen more than a FragmentOne instance, and background log will print out many sets of lifecycle callbacks.

similar:

07-20 08: 18: 46.651: E / FragmentOne (1633): onCreate
07-20 08: 18: 46.651: E / FragmentOne (1633): onCreate
07-20 08: 18: 46.651: E / FragmentOne (1633): onCreate
07-20 08: 18: 46.681: E / FragmentOne (1633): onCreateView
07-20 08: 18: 46.831: E / FragmentOne (1633): onCreateView
07-20 08: 18: 46.891: E / FragmentOne (1633): onCreateView

That is why, because when the screen is rotated, Activity restart occurs, the default Activity Activity will follow in the Fragment re-create; this caused when the rotation when the inherent Fragment restarts, and then executed when the Activity onCreate when will instantiate a new Fragment again, this is the reason arise.

So how to solve it:

In fact, by checking the onCreate parameters Bundle savedInstanceState can determine, whether to re-create the current occurrence Activity:

The default savedInstanceState will store some data, including Fragment instance: by printing can be seen:

07-20 08: 23: 12.952: E / FragmentOne (1782): Bundle [{android: fragments=android.app.FragmentManagerState@40d0b7b8, android: viewHierarchyState = Bundle [{android: focusedViewId = 2131230721, android: views = android. util.SparseArray@40d0af68}]}]

So, we simply change the code only when savedInstanceState == null, it created Fragment instance:

package com.zhy.zhy_fragments;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;

public class MainActivity extends Activity

{
 private static final String TAG = "FragmentOne";
 private FragmentOne mFOne;

 @Override
 protected void onCreate (Bundle savedInstanceState)
 {
  super.onCreate (savedInstanceState);
  requestWindowFeature (Window.FEATURE_NO_TITLE);
  setContentView (R.layout.activity_main);

  Log.e (TAG, savedInstanceState + "");
  
  if (savedInstanceState == null)
  {
   mFOne = new FragmentOne ();
   FragmentManager fm = getFragmentManager ();
   FragmentTransaction tx = fm.beginTransaction ();
   tx.add (R.id.id_content, mFOne, "ONE");
   tx.commit ();
  }
  
 

 }

}

Now, whether there will be only a multiple rotation Fragment instance Activity in.

 

Now there is a problem, that is, when the redraw, Fragment reconstruction occurs, how to maintain the original data?

Activity in fact similar, Fragment there onSaveInstanceState way to save data in this method, then in onCreate or onCreateView or onActivityCreated recovery can be.

Due to space reasons, not posted test code.

5, Fragmeny integrated with ActionBar and MenuItem

Fragment can add your own MenuItem to the ActionBar or alternatively Activity menu.

a, called Fragment of onCreate in setHasOptionsMenu (true);

b, then implement onCreateOptionsMenu in Fragment subclass

c, if you want to deal with MenuItem clicks in Fragment, you can also achieve onOptionsItemSelected; of course Activity can directly handle the MenuItem click event.

Code:

Fragment

package com.zhy.zhy_fragments;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

public class FragmentOne extends Fragment
{

 @Override
 public void onCreate (Bundle savedInstanceState)
 {
  super.onCreate (savedInstanceState);
  setHasOptionsMenu (true);
 }

 @Override
 public View onCreateView (LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState)
 {
  View view = inflater.inflate (R.layout.fragment_one, container, false);
  return view;
 }

 @Override
 public void onCreateOptionsMenu (Menu menu, MenuInflater inflater)
 {
  inflater.inflate (R.menu.fragment_menu, menu);
 }

 @Override
 public boolean onOptionsItemSelected (MenuItem item)
 {
  switch (item.getItemId ())
  {
  case R.id.id_menu_fra_test:
   Toast.makeText (getActivity (), "FragmentMenuItem1", Toast.LENGTH_SHORT) .show ();
   break;
  }
  return true;
 }

}

Activity

package com.zhy.zhy_fragments;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.Toast;

public class MainActivity extends Activity

{
 private static final String TAG = "FragmentOne";
 private FragmentOne mFOne;

 @Override
 protected void onCreate (Bundle savedInstanceState)
 {
  super.onCreate (savedInstanceState);
  requestWindowFeature (Window.FEATURE_NO_TITLE);
  setContentView (R.layout.activity_main);

  Log.e (TAG, savedInstanceState + "");

  if (savedInstanceState == null)
  {
   mFOne = new FragmentOne ();
   FragmentManager fm = getFragmentManager ();
   FragmentTransaction tx = fm.beginTransaction ();
   tx.add (R.id.id_content, mFOne, "ONE");
   tx.commit ();
  }

 }

 @Override
 public boolean onCreateOptionsMenu (Menu menu)
 {
  super.onCreateOptionsMenu (menu);
  . GetMenuInflater () inflate (R.menu.main, menu);
  return true;
 }

 @Override
 public boolean onOptionsItemSelected (MenuItem item)
 {
  switch (item.getItemId ())
  {
  case R.id.action_settings:
   Toast.makeText (this, "setting", Toast.LENGTH_SHORT) .show ();
   return true;
  default:
   // If you want to deal with their own MenuItem Fragment click event, you must not forget to call super.xxx
   return super.onOptionsItemSelected (item);
  }
 }

}

Well, you can well see, Fragment can add MenuItem, can also deal with their own click ~~~

6, no layout effect of Fragment

No layout file Fragment in fact, to save, when Activity restart, save large amounts of data preparation

7, using the Create Fragment dialog box

Finally Fragment related linked together, the above basic Fragment contains all usage ~~~ believe if we can read, must have a lot of harvest ~~~
     
         
         
         
  More:      
 
- CentOS 6.5 install Firefox (Linux)
- Thinking in Java study notes - Access modifiers (Programming)
- To setup CentOS LAMP environment (Server)
- NGINX Plus now fully supports HTTP / 2 (Server)
- Using the Linux folder wc statistics number of lines of code for all files (including subdirectories) (Linux)
- To access an Oracle database using Instant Client (Database)
- Nginx Performance Tuning Guidelines (Server)
- Use Pylint regulate your Python code (Programming)
- About Hibernate cache, you want the latest data have trouble even session.clear (Database)
- Use the Find command to help you find those files that need to be cleaned (Linux)
- Protect your files, modify the Linux value Umask (Linux)
- CentOS / RedHat system partition essential requirements and partition scheme (Linux)
- Configuring a Linux operating system security management services Explain (Linux)
- Linux iptables firewall settings whitelist (RHEL 6 and CentOS 7) (Linux)
- DRBD rapid installation and deployment (Server)
- Android project using the command to create and install the package (Programming)
- CentOS 6.5 installation and simple configuration Nginx (Server)
- MySQL group_con cat_max_Len (Database)
- Linux command in the dialog whiptail (Linux)
- Linux keyboard recording script (Linux)
     
           
     
  CopyRight 2002-2020 newfreesoft.com, All Rights Reserved.