android - 动态添加多个 fragment 到我的 Activity 布局

标签 android

我有一个没有 subview 的线性布局

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


</LinearLayout>

我想根据其中的要求动态添加一个或两个 fragment 。 我知道要向其中添加一个 fragment ,但是如何向其中动态添加两个 fragment 。 我有两个 fragment ,在每个 fragment 中我写了以下 oncreateview

public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        //return super.onCreateView(inflater, container, savedInstanceState);
        View v=inflater.inflate(R.layout.frag1, container, false);
        v.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));

        return v; 
    }

我正在尝试使用以下代码添加,但第二个 fragment 超过了第一个 fragment 。

FragmentTransaction ft=fm.beginTransaction();
        frag1 f=new frag1();
        frag2 ff=new frag2();


        ft.add(android.R.id.content, f);
        ft.add(android.R.id.content, ff);

        ft.commit();

请更新如何做到这一点。 谢谢

最佳答案

这应该可以解决问题:

    FragmentTransaction ft=fm.beginTransaction();
    frag1 f=new frag1();
    frag2 ff=new frag2();
    LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));

    ft.add(android.R.id.content, f).commit();
    FragmentTransaction ft=fm.beginTransaction(); // this line might be unnescessary
    ft.add(android.R.id.content, ff).commit();

关于android - 动态添加多个 fragment 到我的 Activity 布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18935532/

相关文章:

android - ListView 后面缺少按钮

java - AlarmManager 在 Oreo 中安排长时间任务的替代方案是什么?

android - 在Android上的HTML中嵌入youtube视频只有声音,没有视频

android - 通缉 : TableLayout-Like ListView

android - 使用精确关键字搜索 Sqlite 数据库

android - 如何停止或取消 Kotlin 协程(立即停止当前运行的代码块)?

android - 如何在 Intent 中传递 uuid?

android - Android 上的 Tensorflow 对象检测 API

android - SQLiteOpenHelper.setWriteAheadLoggingEnabled 导致错误日志行

android - 如何将网络文件夹挂载到Android内部文件夹?