Android-Fragment learning (1)-201810

Android-Fragment Learning 201810

1. Fragment overview

  A fragment is a UI fragment that can be embedded in an activity. We can think of fragmentation as a sub-activity.

  • Fragments have their own layout, their own behavior and their own life cycle callbacks.
  • While the activity is running, you can add or remove fragments from the activity.
  • You can combine multiple pieces in a single activity to build a multi-column UI.
  • A fragment can be used in multiple activities.
  • The life cycle of a fragment is closely linked to its host activity. This means that the activity is paused and all active fragments are stopped.
  • Fragments can implement behaviors without user interface components.
  • Fragments were added to the Android API in Android 3.0 API 11.

  The advantages of Fragment are as follows:

  • Modularity: We don’t have to write all the code in the Activity, but write the code in their own Fragments.
  • Reusability: Multiple Activities can reuse a Fragment.
  • Adaptability: Different layouts can be easily implemented according to the screen size and screen orientation of the hardware, so that the user experience is better.

2. Fragment static loading

1. First create the fragment layout, left_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/frag_bt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="button"
        android:layout_gravity="center_horizontal"/>

</LinearLayout>

2. Then create this class LeftFragment 

public class LeftFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.left_fragment,container,false);
    }
}

Similarly, right_fragment.xml and RightFragment classes can be created.

3. Modify the layout file and activity class of the activity

<?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="horizontal">

    <fragment
        android:id="@+id/left_fragment"
        android:name="com.example.hjc.hello2.LeftFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        />

    <fragment
        android:id="@+id/right_fragment"
        android:name="com.example.hjc.hello2.RightFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        />

</LinearLayout>
public class SixthActivity extends FragmentActivity{
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sixth);
    }
}

Note: There are two fragments android.support.v4.Fragment and android.app.Fragment. It is recommended to use the v4 package.

Reason: It allows all android systems to maintain functional consistency. For example, nesting Fragment in Fragment is not supported in Android 4.2.

When using v4.Fragment, pay attention to a paragraph in the android.support.v4.Fragment comments:

The main differences when using this support version instead of the framework version are:

If it is not inheritedFragmentActivity类, will report an error android.view.InflateException: Binary XML file line #33: Error inflating class fragment.

Although Fragment can be added in XML, this is just syntactic sugar. Fragment is not a View, but is at the same level as Activity.

 

3. Fragment dynamic loading

The core classes of Fragment are:

  • Fragment: The base class of Fragment. Any created Fragment needs to inherit this class.
  • FragmentManager: manages and maintains Fragments. It is an abstract class, and the specific implementation class is FragmentManagerImpl.
  • FragmentTransaction: Operations such as adding and deleting Fragments need to be performed through transactions. It is an abstract class, and the specific implementation class is BackStackRecord.

1. Modify the layout of the activity. Here you need to use a container to store the fragment. Generally, you can use FrameLayout.

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

    <fragment
        android:id="@+id/left_fragment"
        android:name="com.example.hjc.hello2.LeftFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        />

    <FrameLayout
        android:id="@+id/right_fragment"
        android:name="com.example.hjc.hello2.RightFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        />

</LinearLayout>

2. Add this fragment in the onCreate method of the activity class

public class SixthActivity extends FragmentActivity implements View.OnClickListener{

    private int index=1;
    private List<Fragment> fragList=new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sixth);

        Button frag_bt=findViewById(R.id.frag_bt1);
        frag_bt.setOnClickListener(this);
        
        //newInstance-就是在new RightFragment()
        fragList.add(RightFragment2.newInstance("r2"));
        fragList.add(RightFragment.newInstance("r1"));
        replace(fragList.get(0));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.frag_bt1:
                replace(fragList.get(index));
                index=1-index;
                break;
            default:
                break;
        }
    }

    //切换fragment
    private void replace(Fragment fragment){
        //获取FragmentManager管理类
        FragmentManager fragmentManager=getSupportFragmentManager();
        //打开Fragment事务
        FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
        //replace移除当前容器内所有fragment,添加一个新的fragment
        fragmentTransaction.replace(R.id.right_fragment,fragment,"switcher");
        //提交事务
        fragmentTransaction.commit();
    }

}
  public abstract FragmentTransaction replace(@IdRes int containerViewId, Fragment fragment, @Nullable String tag)-参数(容器的ID,添加的fragment,tag标签)

  For a fragment with a specified tag, you can obtain the fragment object through the findFragmentByTag(String tag) method of FragmentManager.

  In addition to the replace method, there are also add, remove and other methods in FragmentTransaction. Multiple operations can be submitted in one transaction. This is the same as a database transaction, but there is no rollback here. There is only BackStack, which can be added through addToBackStack(String name). After joining, pressing the return key will roll back the last commit (originally pressing return ends the current activity). Usually it is written before commit. The name parameter is optional, usually null is passed.

    //切换fragment
    private void replace(Fragment fragment){
        //获取FragmentManager管理类
        if(fragmentManager==null){
            fragmentManager=getSupportFragmentManager();
        }
        //打开Fragment事务
        FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
        //replace移除当前容器内所有fragment,添加一个新的fragment
        fragmentTransaction.replace(R.id.right_fragment,fragment,FRAG_TAG);
        //加入回退栈test
        fragmentTransaction.addToBackStack("test");
        //提交事务
        fragmentTransaction.commit();
    }

Notice:

  1. When using the FragmentTransaction.add method, you cannot add an existing fragment repeatedly, otherwise java.lang.IllegalStateException: Fragment already added: RightFragment2{b15aabf #1 id=0x7f070067 switcher} will be reported.

   2. The commit() method is an asynchronous operation and can add multiple actions and submit them at once. Internally join the processing queue viamManager.enqueueAction(). The corresponding synchronization method is the commitNow() method.

  3. The commit() method must be used before the onSaveInstance method is called. The reason is: If it is submitted after onSaveInstance, it may conflict with the commit result when the data is restored.

 

4. Life cycle (transfer)

The life cycle of Fragment is similar to that of Activity, but it is more complicated than Activity's life cycle. The basic life cycle method is as follows:

The explanation is as follows:

  • onAttach(): Called when Fragment is associated with Activity. You can get the Activity reference through this method, and you can also get the parameters through getArguments().
  • onCreate(): Called when the Fragment is created.
  • onCreateView(): Create the layout of Fragment.
  • onActivityCreated(): Called when Activity completes onCreate().
  • onStart(): Called when the Fragment is visible.
  • onResume(): Called when the Fragment is visible and interactive.
  • onPause(): Called when the Fragment is not interactive but visible.
  • onStop(): Called when the Fragment is not visible.
  • onDestroyView(): Called when the Fragment's UI is removed from the view structure.
  • onDestroy(): Called when destroying Fragment.
  • onDetach(): Called when the Fragment is disassociated from the Activity.

Among the above methods, only onCreateView() does not need to write the super method when rewriting, the others are required.

Because Fragment depends on Activity, in order to explain the life cycle of Fragment, it needs to be discussed together with the life cycle methods of Activity, that is, the relationship and order of each life cycle method of Fragment and each life cycle method of Activity, as shown in the figure:

 

 

 

 

 

 

参考:

https://developer.android.google.cn/guide/components/fragments

https://cloud.tencent.com/developer/article/1005538

https://xiazdong.github.io/2017/06/15/android-fragment/

https://blog.csdn.net/u011734444/article/details/53347265

 

 

 

Guess you like

Origin blog.csdn.net/ever_who/article/details/81176212
Recommended