[Android's Fragment explanation and simple history page switching effect practice]

content

Section 1 Overview

The second part of the sample effect

The third life cycle

Section 4 Practical Effects


Section 1 Overview

First of all, ask a question, what is Fragment?

Fragment is a UI fragment that can be embedded in Activity. It can make the program make more reasonable and full use of the large screen space , because it is widely used on the tablet.

 You may be a little confused here, what the heck? Here's an example: Imagine that we are developing a page that uses RecyclerView to display a set of news headlines. When one of the headlines is clicked, another interface will open to display the details of the news . If it is designed in a mobile phone, we can put the list of news headlines in one activity and the details of the news in another activity, as shown in the figure.

It doesn't feel like a problem, but when we move the source code to the tablet, the headline of the news will stretch the entire screen (very ugly) and there will be a large blank area . As shown in the figure:

Therefore, when developing, use Fragment reasonably to reduce code costs.

Therefore, a better solution is to put the title list interface and the detailed content interface in two Fragments respectively, and then introduce these two Fragments in the same Activity, so that the screen space can be fully utilized. As shown in the figure:

The second part of the sample effect

So, how to use this Fragment? Let's take a look at the effect of the sample first:

 First create a Fragment (Blank) called   BlankFragment . At this time, AS will automatically create a file called fragment_blank.xml. In the fragment_blank.xml file, we write a text control (TextView) and a button (Button) control:

    <TextView
        android:id="@+id/textview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="到底要选那个呢?"
        android:gravity="center"
        android:textSize="40sp"/>

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="我是按钮"
        android:layout_gravity="center" />

We write in BlankFragment.java file:

package com.example.a2241;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

public class BlankFragment extends Fragment {

    private View root;
    private TextView textView;
    private Button button;

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

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (root == null){
            root = inflater.inflate(R.layout.fragment_blank,container,false);
        }// 这里 inflater.inflate 的用法可以看看这位大佬写的讲解
        //  https://www.cnblogs.com/qinaidexin/p/11726296.html  
        textView = root.findViewById(R.id.textview);// 得到id  textview
        button = root.findViewById(R.id.btn); // 得到id  btn
        button.setOnClickListener(new View.OnClickListener() {// 设置按钮的点击效果事件
            @Override
            public void onClick(View view) {
                textView.setText("发生什么事了?");
            }
        });
        return root;
    }
}

Write in the Acticity_main.xml file:

    <fragment android:name="com.example.a2241.BlankFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/fragment"/>

 Here we can see that only a fragment is set here, how can there be such an effect? Personal understanding here is to refer fragment_blank.xml to Acticity_main.xml and then display it (if there is a mistake, please send a private message for guidance).

The third life cycle

Through the above we know the usage of Fragment, let's take a look at the life cycle of Fragment.

There are four types of activity life cycle: running state, paused state, stopped state and destroyed state .

Fragment's life cycle includes running state, suspended state, stopped state, and destroyed state . As shown in the figure:

Functions of onAttach() and onDetach(): The execution of Fragment must depend on Activity. If there is no Activity, there will be no Fragment. How to identify whether they are bound together? The role of onAttach() is to bind, and the role of onDetach() is to unbind.

The role of onCreate() and onDestroy(): onCreate() Fragment creation, onDestroy() Fragment destruction.

The role of onCreateView() and onDestroyView() : onCreateView() creates Fragment UI, and onDestroyView() destroys Fragment UI.

onActivityCreate() Function: Means that the activity is created.

All that's left is : start, restart, pause, stop.

Let's take a look at the life cycle:

Still the project just now, we continue to write code in the BlankFragment.java file:

package com.example.a2241;

import static androidx.constraintlayout.motion.utils.Oscillator.TAG;

import android.content.Context;
import android.nfc.Tag;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

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

public class BlankFragment extends Fragment {

    private View root;
    private TextView textView;
    private Button button;
  //  private String string = "1";

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG,"onCreate: ");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (root == null){
            root = inflater.inflate(R.layout.fragment_blank,container,false);
        }// 这里 inflater.inflate 的用法可以看看这位大佬写的讲解
        //  https://www.cnblogs.com/qinaidexin/p/11726296.html
        textView = root.findViewById(R.id.textview);// 得到id  textview
        button = root.findViewById(R.id.btn); // 得到id  btn
        button.setOnClickListener(new View.OnClickListener() {// 设置按钮的点击效果事件
            @Override
            public void onClick(View view) {
                textView.setText("发生什么事了?");
            }
        });
        Log.d(TAG,"onCreateView: ");
        return root;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d(TAG, "onActivityCreated: ");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: ");
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "onStart: ");
    }

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

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "onStop: ");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "onDestroyView: ");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d(TAG, "onDetach: ");
    }
}

We click the run button. Open logcat to take a look.

A startup app will call. onCreate, onCreate, onActivityCreated, onStart, onResume .

 Give the conclusion directly (the code will not be shown one by one)

Section 4 Practical Effects

Let's take a look at the practical effect (simple page switching effect):

 Here my click sequence is: button 1 twice, button 2 twice, button 1 below, button 2 once.

The sequence of hitting the return key is: button 1, button 2, button 2, button 2, button 2 .

So how to achieve it?

Create two BlankFragment Fragments (Blank), one is called BlankFragment1 and the other is called BlankFragment2.

BlankFragment1 will create the fragment_blank1.xml file. We directly write the code:

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="我是第一个界面"
        android:textSize="30sp"/>

The same is true for fragment_blank2.xml:

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="我是第二个界面"
        android:textSize="30sp" />

Write in activity_main.xml:

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn1"
        android:text="@string/_1"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn2"
        android:text="@string/_2"/>

    <FrameLayout
        android:id="@+id/fragme_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/teal_200" />

Write the code in MainActivity.java:

package com.example.a2022330;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.example.a2022330.placeholder.BlankFragment2;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

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

        Button button = findViewById(R.id.btn1);
        button.setOnClickListener(this);

        Button button1 = findViewById(R.id.btn2);
        button1.setOnClickListener(this);
    }
    
    public void onClick(View view){
        switch (view.getId()){
            case R.id.btn1:
                replaceFragment(new BlankFragment1());//创建 BlankFragment1()
                break;

            case R.id.btn2:
               replaceFragment(new BlankFragment2());
               break;
        }
    }

    private void replaceFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.fragme_layout,fragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }
}

Just click run.

Finished writing, if you find this article helpful, you can pay attention, (there will be another one tomorrow), (may not finish writing, woo woo woo) . Went to eat, hhh~

Guess you like

Origin blog.csdn.net/aasd23/article/details/123901535