background

Fragment is a concept proposed by Android3.0. The main purpose at that time was to adapt to tablets. It is prepared to Fragment activities, and each part is handled separately. Fragments are lighter than activities, but display similar effects to Actvity, which gives more flexibility in page layout. Previous articles are too old due to Androidx coercion, so I’m writing this series to summarize.

The advantage of the fragments

  • Modularity allows you to write all your code in fragments instead of activities, reducing coupling.
  • Reusable Fragments can be reused by multiple activities.
  • Adaptable ADAPTS to different screen sizes.

Simple use of fragments

Method 1: Static add

Static addition is the practice of using a fragment as a control and embedding it in the Activity’s layout file. This approach is not recommended because it sacrifices the flexibility of the fragment and does not work as well as it should. The FragmentOne and FragmentTwo fragments layout file is as follows

<? The XML version = "1.0" encoding = "utf-8"? > <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:background="@color/colorAccent" android:layout_height="match_parent"> <TextView Android :layout_width="wrap_content" Android :layout_height="wrap_content" Android :text=" This is FragmentOne" Android :layout_centerInParent="true"> </TextView> </ Relativity Ayout > <? 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="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" Android :text=" This is FragmentTwo" Android :layout_centerInParent="true"> </TextView> </ relativity Ayout >Copy the code

The onCreateView method is overridden to return the Fragment view. The Fragment life cycle will be covered in the next article.

public class FragmentOne extends Fragment { @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_one, container, false); return view; } } public class FragmentTwo extends Fragment { @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_two, container, false); }}Copy the code

Add the Fragment as a control to the MainActivity layout file. Note that id and name must be specified. Otherwise, an error will be reported

<? The XML version = "1.0" encoding = "utf-8"? > <FrameLayout 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" tools:context=".MainActivity"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment android:id="@+id/fragment_one" android:layout_width="match_parent" android:layout_weight="1" android:name="com.snow.fragmentdemo.FragmentOne" android:layout_height="match_parent"> </fragment> <fragment android:id="@+id/fragment_two" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:name="com.snow.fragmentdemo.FragmentTwo"> </fragment> </LinearLayout> </FrameLayout>Copy the code

Results the following

Method 2: Dynamic add

Dynamic load is done using the API provided FragmentManager and FragmentTransaction, passed in Androidx getSupportFragmentManager FragmentManager ().

  FragmentManager fm = getSupportFragmentManager();
  FragmentTransaction transaction = fm.beginTransaction();
Copy the code

The following table lists the commonly used apis.

FragmentMananger

The return value function describe
Fragment findFragmentById Get the Fragment by ID
Fragment findFragmentByTag Get the Fragment by Tag
List< Fragment> getFragments Gets all fragments added to the FragmentManager
FragmentTransaction beginTransaction Get FragmentTransaction
#### FragmentTransaction
The return value function describe
—————– ———————— ——————
FragmentTransaction add Add a Fragment to the Container
FragmentTransaction remove Remove a Fragemnt
FragmentTransaction replace Replace the fragments
FragmentTransaction commit Commit the transaction
FragmentTransaction show Display fragments
FragmentTransaction hide Hidden fragments
FragmentTransaction addToBackStack Add things to the rollback stack
##### Precautions
  • Replace: Removes all fragments from FragmentManager before adding them to the Fragment
  • Each item can only be submitted once, otherwise the error is repeated
  • After you call addToBackStack, the physical rollback will be rolled back, and the content of the Fragment page will not change, such as the content in the TextView. If you do not call addToBackStack, the physical rollback will directly exit the Activity.
  • A COMMIT can contain multiple operations, such as add, remove, and so on
The key code
public class MainActivity extends AppCompatActivity implements View.OnClickListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); findViewById(R.id.button1).setOnClickListener(this); findViewById(R.id.button2).setOnClickListener(this); } @Override public void onClick(View v) { FragmentManager fm = getSupportFragmentManager(); switch (v.getId()) { case R.id.button1: FragmentTransaction transaction = fm.beginTransaction(); transaction.replace(R.id.content, new FragmentOne()); transaction.commit(); break; case R.id.button2: FragmentTransaction transaction2 = fm.beginTransaction(); transaction2.replace(R.id.content, new FragmentTwo()).commit(); break; }}}Copy the code

The last

Androidx Fragment life cycle (2