mvvm databinding include用法

可能是我的性格原因,话比较少直接入正题,没有什么要说的,呵呵,直接上代码,先看include.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable name="base" type="com.business.sbl.model.bean.BaseTitleBean"/>
    </data>
    <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="55dp"
            android:background="@color/white">
        <TextView
                android:id="@+id/tv_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:text="@{base.title}"
        />
        <ImageView
                android:id="@+id/img_right"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
    </RelativeLayout>
</layout>

再看basetitlebean类

class BaseTitleBean(val title:String)

就这么简单,如果要图片的话,再加个图片地址就好了,这里直接加的title

在看fragment或者activity布局

<?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">
    <data >
        <variable name="home" type="com.business.sbl.viewmodel.HomeViewModel"/>
        <variable name="base" type="com.business.sbl.model.bean.BaseTitleBean"/>
    </data>
    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
        <include layout="@layout/base_head" app:base="@{base}"/>
        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="@string/please_enter"/>

    </LinearLayout>
</layout>

在一个布局中引用了两个variable,应该可以引用很多,因为是新手,所以暂时引用了两个,而include 多了一个app:base,好像可以用bind:来实现,重要的是要加xmlns:app="http://schemas.android.com/apk/res-auto",这个App:base用的是上面定义的base而后面的base就是include布局中的name的base。

在看看代码中的引用:

private lateinit var mBinding: FragmentHomeBinding
    override fun initViews() {
        mBinding = DataBindingUtil.inflate(inflater,R.layout.fragment_home,null,false)
        v= mBinding.root
        val titleBean = BaseTitleBean("首页")
        mBinding.base = titleBean
    }

用到那个布局直接.名字就好了。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值