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();
}
}
动态创建的基本的简单流程基本上这样
作者:冰稀饭Aurora
出处:https://www.cnblogs.com/rsy-bxf150/p/17249822.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端