[Android UI] Fragment creation, addition, deletion, life cycle

Basic knowledge:
what is fragment:

  • Fragment is part of the activity interface
  • Multiple fragments are combined into one activity
  • Multiple fragments can reuse an activity

to sum up:

  • Fragment is equivalent to a modular activity
  • Has its own life cycle and receives its own events
  • Added or deleted while the activity is running

Why use fragment:

  • Support more dynamic and flexible interface design
  • Use on tablet
  • The layout of the activity is divided into fragments

0, create a new Fragment

TestFragment.java

package com.jsc4.aboutactivity;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link TestFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TestFragment extends Fragment {
    
    

    public static final String TAG = TestFragment.class.getSimpleName();
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public TestFragment() {
    
    
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment TestFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static TestFragment newInstance(String param1, String param2) {
    
    
        TestFragment fragment = new TestFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
    
    
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        Log.i(TAG, "onCreate");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    
    
        Log.i(TAG, "onCreateView");
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_test, container, false);//从xml得到一个view
        TextView textView = view.findViewById(R.id.test_text_view);//获得了view后,可以从中得到控件
        textView.setText("just test");//进而修改控件的属性
        return view;
    }

    @Override
    public void onPause() {
    
    
        super.onPause();
        Log.i(TAG, "onPause");
    }

    @Override
    public void onDestroy() {
    
    
        super.onDestroy();
        Log.i(TAG, "onDestroy");
    }
}

xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:background="@color/red"
    tools:context=".TestFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:id="@+id/test_text_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment" />
</FrameLayout>

1. Create Activity to store fragment

Create a new TestFragmentActivity
java file:

package com.jsc4.aboutactivity;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class TestFragmentActivity extends AppCompatActivity {
    
    

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

xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/colorAccent"
    tools:context=".TestFragmentActivity">

</LinearLayout>

2. Add fragment through XML

Add fragment to the Activity's xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/colorAccent"
    tools:context=".TestFragmentActivity">

    <fragment
        android:id="@+id/fragment_test1"
        android:name="com.jsc4.aboutactivity.TestFragment"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        />

    <fragment
        android:id="@+id/fragment_test2"
        android:name="com.jsc4.aboutactivity.TestFragment"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        />

    <fragment
        android:id="@+id/fragment_test3"
        android:name="com.jsc4.aboutactivity.TestFragment"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        />

</LinearLayout>

3. Add fragment through java

to sum up:

查找fragment:
findFragmentById()
findFragmentByTag()

Fragment的后退:
Fragment Stack
popBackStack()
addOnBackStackChangedListener()

总结:
FragmentManager
FragmentTransaction
Add
Remove

Add fragment through java:

package com.jsc4.aboutactivity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;

public class TestFragmentActivity extends AppCompatActivity {
    
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_fragment);
	
		关键代码在这里:
		
        FragmentManager fragmentManager = getSupportFragmentManager();  // 找到校长
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();  // 找到秘书

        TestFragment testFragment = TestFragment.newInstance(null, null);  // 创建一个fragment
        fragmentTransaction.add(R.id.fragment_view, testFragment).commit();  // 最后要commit,向校长汇报
    }
}

4. Delete fragment through java:

Only commit once:

package com.jsc4.aboutactivity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;

public class TestFragmentActivity extends AppCompatActivity {
    
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_fragment);
	
		关键代码在这里:
		
        FragmentManager fragmentManager = getSupportFragmentManager();  // 找到校长
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();  // 找到秘书

       TestFragment testFragment = TestFragment.newInstance(null, null);  // 创建一个fragment
        fragmentTransaction.add(R.id.fragment_view, testFragment);  // 只需commit一次

        fragmentTransaction.remove(testFragment).commit();  // 最后要commit,向校长汇报
    }
}

5. Find the fragment through java

Find the fragment by Id:

添加方式为:
fragmentTransaction.add(R.id.fragment_view, testFragment);  // 全局只需commit一次


查找方式为:
Fragment fragment = fragmentManager.findFragmentById(R.id.fragment_test1);  // 找到fragment
if(fragment instanceof TestFragment){
    
    
    // 如果是TestFragment类型
    Log.i(TAG, "onCreate:fragment类型是TestFragment");
}else{
    
    
    throw new IllegalStateException("this is not TestFragment");
}

Find the fragment by tag:

添加方式为:
fragmentTransaction.add(R.id.fragment_view, testFragment, "test_fragment_view");//通过tag的方式添加实例


查找方式为:        
Fragment fragment1 = fragmentManager.findFragmentByTag("test_fragment_view");  // 通过tag找到fragment

6, Fragment life cycle

Insert picture description here
Activity life cycle:
Insert picture description here

Comparison of the two:
Insert picture description here

Three states of fragment: Resumed (interacting with the user), Paused (suspended), and Stoped (stopped)

Guess you like

Origin blog.csdn.net/qq_30885821/article/details/108812874