Two implementation methods of Android's Fragment embedded in activities

Two implementation methods of Android's Fragment embedded in activities


Fragment is a UI fragment used to embed into an activity, similar to Jpanel in Java.
Generally speaking, activities can realize the content of Fragment, so why do we need Fragment?
The main reasons are:

  1. Fragment can improve code reusability
  2. Switching between Fragments faster than activities
  3. Fragment is compatible with mobile phones and tablets, and displays different interfaces according to device types

Like an activity, each Fragment corresponds to a layout file. The layout file of LeftFragment.java in this article is fragment_left.xml, and the layout file of RightFragment.java is fragment_right.xml.
This article uses an example to explain separately, creating a MainActivity and two Fragments, namely LeftFragment and RightFragment; the layout of MainActivity is divided into left and right. part, embed LeftFragment into the left half and RightFragment into the right half.

The codes of LeftFragment.java and fragment_left.xml files are as follows:

public class LeftFragment extends Fragment {
    
    
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    
    
        View view = inflater.inflate(R.layout.left_fragment, container, false);
        return view;
    }
}
<?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"
    android:background="#FF0000">
    <TextView
        android:id="@+id/left_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="这是LeftFragment的TextView"/>
</LinearLayout>

The codes of RightFragment.java and fragment_right.xml files are as follows:

public class RightFragment extends Fragment {
    
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    
    
        View view = inflater.inflate(R.layout.right_fragment, container, false);
        return view;
    }
    public void fun(){
    
    
        System.out.println("调用RightFragment的fun()");
    }
}
<?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"
    android:background="#00FF00">
    <TextView
        android:id="@+id/right_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="这是RightFragment的TextView"/>
</LinearLayout>

The above is the code of LeftFragment and RightFragment and their corresponding layout files.
There are two ways to embed Fragment in an activity, as follows:

1. The layout file corresponding to the activity references Fragment

MainActivity.java file without any modification, the corresponding activity_main.xml file code is as follows

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="horizontal"
    tools:context=".MainActivity">
    <fragment
        android:id="@+id/left_fragment"
        android:name="com.example.fragmentapplication.LeftFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        />
    <fragment
        android:id="@+id/right_fragment"
        android:name="com.example.fragmentapplication.RightFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        />
</LinearLayout>

This method is to statically load Fragment. In the onCreate() method of MainActivity, the operations that can be performed on Fragment are as follows:

  1. MainActivity calls the RightFragment component:
	TextView right = findViewById(R.id.right_text);
  1. MainActivity calls the method of RightFragment:
	RightFragment rightFragment = (RightFragment) getSupportFragmentManager().findFragmentById(R.id.right_fragment);
	rightFragment.fun();

2. Activity reference Fragment

MainActivity.java file and activity_main.xml file code are as follows:

public class MainActivity extends AppCompatActivity {
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        replaceFragment(R.id.left_layout, new LeftFragment());
        replaceFragment(R.id.right_layout, new RightFragment());
    }

    // 动态添加Fragment
    @SuppressLint("ResourceType")
    private void replaceFragment(int layout, Fragment fragment){
    
    
        // 1、通过getSupportFragmentManager()方法创建Fragment的管理器对象
        FragmentManager fragmentManager = getSupportFragmentManager();
        // 2、通过beginTransaction()方法获取Fragment的事务对象并且开启事务
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        // 3、向容器内添加、替换、删除Fragment
        transaction.add(layout, fragment);       //  添加碎片
//        transaction.replace(R.id.right_layout, fragment);   // 替换碎片
//        transaction.remove(fragment);                       // 移除fragment
        // 将Fragment以栈的方式进行存储,替换时将新的Fragment压栈,点击back按钮时,将当前Fragment出栈,显示前一个Fragment
        transaction.addToBackStack(null);
        // 提交事务
        transaction.commit();
    }
}
<?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="horizontal"
    tools:context=".MainActivity">
    <LinearLayout
        android:id="@+id/left_layout"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical">
    </LinearLayout>
    <LinearLayout
        android:id="@+id/right_layout"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical">
    </LinearLayout>
</LinearLayout>

This method is to dynamically load Fragment, and the components and methods of Fragment cannot be directly called in the onCreate() method of MainActivity. It needs to be called in the onStart() method of MainActivity. The reason is that when Activity's onCreate is called, Fragment's onCreateView has not been called yet, resulting in no view object being generated. For details, you can refer to the life cycle of Activity and Fragment.
Call the components and methods of RightFragment in the onStart() method of MainActivity:

@Override
protected void onStart() {
    
    
     super.onStart();
     // MainActivity调用RightFragment的组件
     TextView text = findViewById(R.id.right_text);
     text.setText("Hello RightFragment");

     // MainActivity调用RightFragment的方法
     RightFragment rightFragment = (RightFragment) getSupportFragmentManager().findFragmentById(R.id.right_layout);
     rightFragment.fun();
}

Guess you like

Origin blog.csdn.net/qq_34205684/article/details/110135186