我的 fragment 中有一个字符串变量,我想在带有数据绑定(bind)的 XML 中使用它 这是我的 fragment
class HomeFragment : Fragment() {
var struc: String = "Organization Structure"
lateinit var binding: FragmentHomeBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding = FragmentHomeBinding.inflate(inflater, container, false)
return binding.getRoot()
}}
这是 XML
<?xml version="1.0" encoding="utf-8"?>
<layout 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">
<data>
<variable
name="data"
type="com.mountmeru.view.HomeFragment" />
</data>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".view.HomeFragment">
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/tvOrganization"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/ivOrganization"
android:layout_marginTop="20dp"
android:gravity="center"
android:text="@{data.struc}"
android:textAlignment="center"
android:textColor="@color/mountmerured"
android:textSize="15sp" />
</FrameLayout></layout>
当我运行应用程序时, TextView 文本永远不会设置。
这里出了什么问题?
最佳答案
第一种方法:
This not direct way which you asked. But you can also do using data class, this is little bit long way but you can add multiple data.
创建数据类
data class Data(var struc: String = "Organization Structure")
在 xml 中添加此内容
<data> <variable name="dataModel" type="Data" /> // here data class path of step1 </data> <FrameLayout android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".view.HomeFragment"> <androidx.appcompat.widget.AppCompatTextView android:id="@+id/tvOrganization" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/ivOrganization" android:layout_marginTop="20dp" android:gravity="center" android:text="@{dataModel.struc}" // use like this android:textAlignment="center" android:textColor="@color/mountmerured" android:textSize="15sp" /> </FrameLayout></layout>
在 Activity 或 fragment 中
private fun setData() { val data = Data(struc= "Organization") bindObject.dataModel = data }
第二种方式:
或者直接的方式是
<data>
<variable
name="struc"
type="String" />
</data>
以及来自 Activity/fragment
bindObject.struc = "Organization Structure";
第三种方式:
或者在您的情况下,您需要在 onCreateView 中执行此操作,一切正常
binding.data = this;
关于android - 从 fragment 中的变量进行数据绑定(bind),android?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62260330/