ViewBinding(3) — ViewBinding在fragment中使用

前言

在之前我们已经讲过ViewBindingActivity中的使用了,大家感兴趣的话,可参考以下文章:
ViewBinding(1) — 在Activity中使用
ViewBinding(2) — Activity中ViewBinding和include标签使用
今天我们来讲讲ViewBindingfragment中的使用吧
今天涉及内容:

  1. Fragment 原始初始化方式
  2. ViewBinding在fragment中初始化控件
  3. 项目结构图和效果图

效果图如下:


2.gif

一. Fragment 原始初始化方式

先贴出Fragment布局文件fragment_one.xml的代码:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".ui.MainActivity"
    android:background="#ff0000">

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.08" />

</androidx.constraintlayout.widget.ConstraintLayout>

Fragment原始初始化控件代码如下:

/**
 * Title:
 * description:
 * autor:pei
 * created on 2022/7/28
 */
class OneFragment :Fragment(){

    private lateinit var mLayoutView: View
    private lateinit var mContext: Context
    private lateinit var mTvName: TextView

    private lateinit var mFragmentBinding: FragmentOneBinding

    override fun onAttach(context: Context) {
        super.onAttach(context)

        this.mContext = getContext() as AppCompatActivity
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mLayoutView=inflater.inflate(R.layout.fragment_one,container,false)
        mTvName=mLayoutView.findViewById(R.id.tv_name)
        //获取activity传过来的bundle值
        mTvName.text=requireArguments().getString("One").toString()
        return mLayoutView
    }
}

二. ViewBindingfragment中初始化控件

在我们使用了ViewBinding后,在fragment中初始化控件如下:

还有 44% 的精彩内容
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
支付 ¥2.00 继续阅读

推荐阅读更多精彩内容