在使用视图绑定时,我遇到了一些未记录的情况。
第一:我如何获得绑定包含视图布局部分?主绑定只能看到在主布局中定义的项。
第二:如何获得合并布局部分的绑定。同样,主绑定只看到主布局中的项目?
在使用视图绑定时,我遇到了一些未记录的情况。
第一:我如何获得绑定包含视图布局部分?主绑定只能看到在主布局中定义的项。
第二:如何获得合并布局部分的绑定。同样,主绑定只看到主布局中的项目?
当前回答
在我的例子中,我忘记将id分配给include标记
现在,当你赋值了id,你就能得到绑定对象,
YourMainLayoutBinding.YourIncludeTagIDLayoutBinding
其他回答
如果你想绑定包含布局,
活动
YourMainLayoutBinding mainLayoutBinding = MainLayoutBinding.inflate(getLayoutInflater);
View view = mainLayoutBinding.getRoot();
YourIncludedLayoutBinding includedLayoutBinding = YourIncludedLayoutBinding.bind(View);
的片段
YourMainLayoutBinding mainLayoutBinding = MainLayoutBinding.inflate(inflater,container,false);
View view = mainLayoutBinding.getRoot();
YourIncludedLayoutBinding includedLayoutBinding = YourIncludedLayoutBinding.bind(View);
确保你的主布局绑定父根是LinearLayout, incledlayoutbinding父布局也是线性布局
使用数据绑定库。然后用<layout>标签包装XML布局
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
...
<include
android:id="@+id/toolbar"
layout="@layout/toolbar" />
...
</LinearLayout>
</layout>
toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/ivImage"
... />
<TextView
android:id="@+id/tvTitle"
... />
</LinearLayout>
MainActivity.kt
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
// Access include layout views
binding.toolbar.rootView.ivImage.setImageResource(R.drawable.ic_back_arrow)
binding.toolbar.rootView.tvTitle.text = getString(R.string.home)
...
}
遵循步骤:
private val binding: FragmentBinding 由viewBinding (FragmentBinding:绑定) 确保在“onViewCreated(view: view, savedInstanceState: Bundle?)”中执行以下操作 Val binding2 = binding.root.include_layout_id
例如val binding2 = binding.root.tool_bar_layout
现在访问你的include布局,视图。如。
binding2.textView.text = "your text"
在包含布局中,你必须创建一个容器布局,并在这里放置id。
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/example"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent">
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
在我的例子中,我忘记将id分配给include标记
现在,当你赋值了id,你就能得到绑定对象,
YourMainLayoutBinding.YourIncludeTagIDLayoutBinding