Fragment的动态创建
Fragment的动态创建
动态创建不同于静态创建,不需要写固定的xml文件,但是依然要有一个xml文件来当容器。
1.我们需要使用<androidx.fragment.app.FragmentContainerView/>
<?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" tools:context=".DynamicFragmentActivity"> <androidx.fragment.app.FragmentContainerView android:id="@+id/frag_dy_1" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
2.动态创建还需要在java代码中加入相应的动态创建的代码
package com.example.dataapplication; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import android.os.Bundle; import com.example.dataapplication.fragment.BlankFragment1; import com.example.dataapplication.fragment.BlankFragment2; public class DynamicFragmentActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dynamic_fragment); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.add(R.id.frag_dy_1, BlankFragment2.class, null).commit(); } }