美文网首页
Fragment的动态添加

Fragment的动态添加

作者: 会写代码的小猿猴 | 来源:发表于2021-05-25 09:23 被阅读0次

不啰嗦直接上代码
创建一个FragMent命名为FirstFragment,代码:

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.Nullable
import androidx.fragment.app.Fragment


@SuppressLint("ValidFragment")
class FirstFragment() : Fragment() {
    private var mTextView: TextView? = null

    @Nullable
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val view: View = inflater.inflate(R.layout.first_fragment, container, false)
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mTextView = view.findViewById(R.id.txt_content)
        mTextView!!.text = "this is a Fragment!"
    }
}

FirstFragment的布局文件代码

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/txt_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textSize="20sp"/>
</LinearLayout>

MainActivity代码

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        var button = findViewById<Button>(R.id.enter)
        button.setOnClickListener{
            supportFragmentManager//获取到fragmentManager
                .beginTransaction()//开启事务
                .add(R.id.fragment_container, FirstFragment())//添加碎片或者可以用replace
                .commit()//提交事务
        }
    }
}

MainActivity布局文件代码:

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat 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:orientation="vertical"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/enter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter" />

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    </FrameLayout>

</androidx.appcompat.widget.LinearLayoutCompat>

相关文章

网友评论

      本文标题:Fragment的动态添加

      本文链接:https://www.haomeiwen.com/subject/fjjqsltx.html