1.作用
1.性能优化:
用到的时候再去加载,不调用加载的话,不会显示
2.使用
1.xml
其中hecate_listview2x为里面加载的布局
<ViewStub
android:id="@+id/hecate1_recycler_vs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout="@layout/hecate_listview2x"
/>
2.Java代码
- 一定要先设置加载监听setOnInflateListener,再调用加载inflate(),不然会报错
class MainActivity : ComponentActivity() {
private lateinit var mainBinding: ActivityMainBinding
private lateinit var hecateListview2xBinding: HecateListview2xBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mainBinding= ActivityMainBinding.inflate(layoutInflater)
setContentView(mainBinding.root)
//viewStub加载布局的监听方法
mainBinding.hecate1RecyclerVs.setOnInflateListener { viewStub, view ->
hecateListview2xBinding= HecateListview2xBinding.bind(view)//viewbinding绑定viewStub里面的布局
}
//viewStub加载
mainBinding.hecate3RecyclerVs.inflate()
//对viewStub加载布局里面的view方法的调用
hecateListview2xBinding.textView.setOnClickListener {
Toast.makeText(
this,
"我是textView",
Toast.LENGTH_SHORT
).show() }
}
}