前言
在之前我们已经讲过ViewBinding
在Activity
中的使用了,大家感兴趣的话,可参考以下文章:
ViewBinding(1) — 在Activity中使用
ViewBinding(2) — Activity中ViewBinding和include标签使用
今天我们来讲讲ViewBinding
在fragment
中的使用吧
今天涉及内容:
- Fragment 原始初始化方式
- ViewBinding在fragment中初始化控件
- 项目结构图和效果图
效果图如下:
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
}
}
二. ViewBinding
在fragment
中初始化控件
在我们使用了ViewBinding
后,在fragment
中初始化控件如下: