动态加载,就是使用代码进行加载,不指定name属性。

 

使用帧布局元素,进行覆盖显示。

添加一个fragement需要4个步骤。

1.获取Fragment管理器

2.获取Fragment事务(/开启事务)

3.动态添加Fragment
        //参数1:容器id
        //参数2:Fragment对象

4.提交事务

fragment (动态加载)

 

 

package com.example.fragment_static;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //FragmentManager   FragmentTransaction

        //1.获取Fragment管理器
        FragmentManager manager = getSupportFragmentManager();

        //2.获取Fragment事务(/开启事务)
        FragmentTransaction transaction = manager.beginTransaction();

        //3.动态添加Fragment
        //参数1:容器id
        //参数2:Fragment对象
        final Fragment f2 = new Fragment2();
        transaction.add(R.id.container,f2);

        //4.提交事务
        transaction.commit();

    }
}
View Code

相关文章:

  • 2021-04-18
  • 2022-12-23
  • 2022-12-23
  • 2021-06-22
  • 2022-02-18
  • 2021-06-09
  • 2021-06-11
  • 2022-12-23
猜你喜欢
  • 2021-04-12
  • 2022-12-23
  • 2021-11-09
  • 2022-12-23
  • 2021-08-17
  • 2021-05-20
相关资源
相似解决方案