databinding 入门 知识 给TextView 赋值

半世苍凉 提交于 2019-12-10 12:51:44

在上一张中记录怎样创建布局的 这里就不说了下面写2个textview 具体代码如下

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable
            name="user"
            type="com.hxm.User"/>
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/colorPrimary"
            android:text="@{user.name}"/>


        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/colorPrimary"
            android:text="@{user.age}"/>

    </LinearLayout>
</layout>

type 为包名+ 自己命名的bean

代码中

分为三部把

1.获取<data />标签对象

2.创建User对象
3.绑定到user到布局对象中

具体代码如下

public class LoginActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState){

        super.onCreate(savedInstanceState);
        // 1.获取<data />标签对象
        LoginActivityLayoutBinding binding= DataBindingUtil.setContentView(this,R.layout.login_activity_layout);
        // 2.创建User对象
        User user = new User("胡小牧","26");
        // 3.绑定到user到布局对象中
        binding.setUser(user);
    }
}

demo 参考地址

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!