Fragment

简单写法(静态添加):

分别建立两个fragment布局:left_fragment.xml 和 right_fragment.xml

然后创建两个类,都继承自Fragment类,代码如下:

class LeftFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.left_fragment, container, false)
    }
}

两个类似。

然后在activity_main.xml中定义两个fragment,代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="horizontal"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment
        android:id="@+id/leftFrag"
        android:name="com.example.fragmenttest.LeftFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <fragment
        android:id="@+id/rightFrag"
        android:name="com.example.fragmenttest.RightFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

</LinearLayout>

使用<fragment>标签在布局中添加Fragment,需要通过android:name属性来显式声明要添加的Fragment类名,注意一定要将类的包名也加上。

高级技巧:动态加载fragment

Fragment真正的强大之处在于,它可以在程序运行时动态地添加到Activity当中。根据具体情况来动态地添加Fragment,你就可以将程序界面定制得更加多样化!

动态添加Fragment主要分为5步:
(1) 创建待添加Fragment的实例。创建一个新的fragment布局,同时创建新fragment的类用来加载刚创建的布局,同时修改activity_main.xml中的内容,将需要动态加载的改成FrameLayout控件。
(2) 获取FragmentManager,在Activity中可以直接调用getSupportFragmentManager()方法获取。
(3) 开启一个事务,通过调用beginTransaction()方法开启。
(4) 向容器内添加或替换Fragment,一般使用replace()方法实现,需要传入容器的id和待添加的Fragment实例。
(5) 提交事务,调用commit()方法来完成。
代码如下:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val button: Button = findViewById(R.id.button1)
        button.setOnClickListener{
            replaceFragment(AnotherRightFragment())
        }
    }

    private fun replaceFragment(fragment: Fragment) {
        val fragmentManager = supportFragmentManager
        val transaction = fragmentManager.beginTransaction()
        transaction.replace(R.id.rightLayout, fragment)
        transaction.commit()
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值