Follow Android 007, get a full set of Free Android development learning materials

What is a Fragment

An Activity is the entire interface that you see, while an Activity can continue to split into multiple fragments. Fragments were originally used to make the most of space on tablets, but they are also commonly used on mobile devices, mainly to share a single area of the screen. For example, in the following interface, the blue box above is the display area shared by several functions (recommendation, application, game, etc.). When users switch to different function pages, the contents of the shared display area will be replaced with the corresponding function Fragment.

Use a single Fragment sample

Effect:

Creating a Fragment manually

  1. Right-click in the project directory and choose “New>Fragment>Fragment(Blank)”

2. In the window, set the Fragment name corresponding to the layout file name.3. The Fragment created by default is a bit complex and can be simplified as follows:

class BlankFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup? , savedInstanceState:Bundle?).: View? {
        return inflater.inflate(R.layout.fragment_blank, container, false)}}Copy the code
  1. Add a container for the Fragment layout to the Activity layout file

Modify activity_main. XML and add a FrameLayout named containerLayout.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/containerLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
Copy the code

Load the Fragment in the Activity

The following shows a jump from MainActivity to Main2Activity when clicking the Button1 button

replaceFragment(BlankFragment(), R.id.containerLayout)
Copy the code

The complete code is as follows:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?). {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        replaceFragment(BlankFragment(), R.id.containerLayout)
    }

    private fun replaceFragment(fragment: Fragment, containerId: Int) =
        supportFragmentManager.beginTransaction().replace(containerId, fragment).commit()
}
Copy the code

Use multiple Fragment samples

Multiple Fragments display content in the same area. You can switch between them using tabs.

rendering

Create the first Fragment and the corresponding layout file

  • The first Fragment
class FirstFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup? , savedInstanceState:Bundle?).: View? {
        return inflater.inflate(R.layout.fragment_first, container, false)}}Copy the code
  • The first Fragment corresponds to the layout :fragment_first.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="First Fragment" />

</FrameLayout>
Copy the code

Create a second Fragment and the corresponding layout file

  • The second Fragment
class SecondFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup? , savedInstanceState:Bundle?).: View? {
        return inflater.inflate(R.layout.fragment_second, container, false)}}Copy the code
  • The second Fragment corresponds to the layout :fragment_second.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Second Fragment" />

</FrameLayout>
Copy the code

Modify the Activity’s corresponding layout file to show two bottom tabs.

The following code shows a layout with the ID bottomLayout and two tags that you can click to switch the contents of containerLayout at the top of the page.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <FrameLayout
        android:id="@+id/containerLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottomLayout" />

    <LinearLayout
        android:id="@+id/bottomLayout"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:background="#F8F8F8">

        <TextView
            android:id="@+id/page1Tv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="TAB Page 1" />

        <View
            android:layout_width="1px"
            android:layout_height="match_parent"
            android:background="#E7E7E7" />

        <TextView
            android:id="@+id/page2Tv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="TAB Page 2" />
    </LinearLayout>
</RelativeLayout>
Copy the code

Fragment loading and switching in the Activity code

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?). {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // The first Fragment is loaded by default
        replaceFragment(FirstFragment(), R.id.containerLayout)
        // Add a click event to the page1Tv control and switch to FirstFragment after clicking
        page1Tv.setOnClickListener { replaceFragment(FirstFragment(), R.id.containerLayout) }
        // Add a click event to the page2Tv control and switch to SecondFragment
        page2Tv.setOnClickListener { replaceFragment(SecondFragment(), R.id.containerLayout) }
    }

    private fun replaceFragment(fragment: Fragment, containerId: Int) =
        supportFragmentManager.beginTransaction().replace(containerId, fragment).commit()
}
Copy the code

Complete source code

Gitee.com/cxyzy1/frag…


Android development tutorial series summary

Development language learning

Kotlin language basics

UI control learning series

UI control _TextView UI control _EditText UI control _Button UI control _ImageView UI control _RadioButton UI control _CheckBox UI control _ProgressBar

Follow the headlines to get the latest articles: