android jetpack databinding的基本使用(java)

这篇具有很好参考价值的文章主要介绍了android jetpack databinding的基本使用(java)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

databing的基本使用

  1. 开启databing
android {
	........

    dataBinding{

        enable = true
    }
}
  1. 修改布局文件
    为布局文件添加<layout>标签。
<?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">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/main_tv_word"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="13dp"
            android:text="句子" />

        <TextView
            android:id="@+id/main_tv_def"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="13dp"
            android:text="句子2" />



    </LinearLayout>
</layout>
  1. 实例化布局文件
    ActivityMainBinding activityMainBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
    }
  1. 向布局文件传递数据

创建一个Sentence 类,实例化。传给布局并显示。

public class Sentence {

    private String sentence;


    private String sentenceCH;


	getter/setter......
}
<?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="sentence"
            type="cn.jn.mytest.entity.Sentence" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/main_tv_word"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="13dp"
            android:text="@{sentence.sentence}" />

        <TextView
            android:id="@+id/main_tv_def"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="13dp"
            android:text="@{sentence.sentenceCH}" />


    </LinearLayout>
</layout>
    ActivityMainBinding activityMainBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);

        Sentence sentence = new Sentence();
        sentence.setSentence("Hello");
        sentence.setSentenceCH("你好");
        activityMainBinding.setSentence(sentence);

    }

android jetpack databinding的基本使用(java) 5. 在布局中引用静态类
在sentence类中添加属性collect ,collect 等于1表示已收藏,0表示收藏。
建立工具类CollectUtil

public class CollectUtil {
    public static String getCollectString(int collect) {

        if (collect == 1) {

            return "已收藏";
        } else {

            return "未收藏";
        }
    }
}

通过<import>导入到布局文件中

    <data>

        <variable
            name="sentence"
            type="cn.jn.mytest.entity.Sentence" />

        <import type="cn.jn.mytest.util.CollectUtil" />
    </data>

调用CollectUtil

<?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="sentence"
            type="cn.jn.mytest.entity.Sentence" />

        <import type="cn.jn.mytest.util.CollectUtil" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/main_tv_word"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="13dp"
            android:text="@{sentence.sentence}" />

        <TextView
            android:id="@+id/main_tv_def"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="13dp"
            android:text="@{sentence.sentenceCH}" />


        <TextView
            android:id="@+id/main_tv_collect"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="13dp"
            android:text="@{CollectUtil.getCollectString(sentence.collect)}" />


    </LinearLayout>
</layout>

android jetpack databinding的基本使用(java)

二级页面的绑定

当我们在activity或者fragment的布局中,使用<include>引入的布局叫二级页面。

一级页面


    <data>

        <variable
            name="sentence"
            type="cn.jn.mytest.entity.Sentence" />

        <import type="cn.jn.mytest.util.CollectUtil" />
    </data>
   <include
            layout="@layout/toolbar"
            app:sentence="@{sentence}" />

二级页面需要创建个相同名字的变量

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

        <variable
            name="sentence"
            type="cn.jn.mytest.entity.Sentence" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/toolbar_tv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{sentence.sentence}" />

    </LinearLayout>
</layout>

自定义BindingAdapter

bindingadapter中的方法都是静态方法,需要添加@BindingAdapter,第一个参数为控件本身,第二个参数是布局文件传过来参数,

public class TextBindingAdapter {
    @BindingAdapter("collect")
    public static void setCollect(TextView textView, int collect) {

        if (collect == 1) {

            textView.setTextColor(Color.GREEN);
            textView.setText("已收藏");
        } else {

            textView.setTextColor(Color.GRAY);
            textView.setText("未收藏");
        }
    }
}	
        <TextView
            android:id="@+id/main_tv_collect"
            collect="@{sentence.collect}"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="13dp" />

android jetpack databinding的基本使用(java)

自定义BinddingAdapter的可选旧值

oldcollect是旧值,newCollect是新值。可以用来防止重复调用。

    @BindingAdapter("collect")
    public static void setCollect(TextView textView, int oldCollect, int newCollect) {


        if (oldCollect == newCollect) {

            return;
        }

        if (newCollect == 1) {

            textView.setTextColor(Color.GREEN);
            textView.setText("已收藏");
        } else {

            textView.setTextColor(Color.GRAY);
            textView.setText("未收藏");
        }
    }
        <TextView
            android:id="@+id/main_tv_collect"
            collect="@{sentence.collect}"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="13dp" />

双向绑定

前面的所涉及的绑定是单向绑定,根据字段来更新控件的内容。
通过交互修改edittext 的内容,使得对应的字段自动更新。
实现

public class NameModel {

    public String name;
}

创建一个双向绑定的业务逻辑类,继承BaseObservable 。给getter添加@Bindable,对字段进行双向绑定。setter方法会在用户编辑edittext时自动调用,内容更新后,会调用notifyPropertyChanged方法,通知观察者,数据已更新,更新ui。

public class NameViewModel extends BaseObservable {

    private NameModel nameModel;


    public NameViewModel() {

        nameModel = new NameModel();
        nameModel.name = "zhang san";
    }


    @Bindable
    public String getName() {


        return nameModel.name;
    }

    public void setName(String name) {

            nameModel.name = name;
            notifyPropertyChanged(BR.name);
    }
}

在布局中的使用,@{}变乘@={}。
main_tt_name2是textview,这个为了调用notifyPropertyChanged后,能够直观的看到内容变化。

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

        <variable
            name="nameViewModel"
            type="cn.jn.mytest.observable.NameViewModel" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">


        <EditText
            android:id="@+id/main_et_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@={nameViewModel.name}" />

        <TextView
            android:id="@+id/main_tt_name2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{nameViewModel.name}" />

    </LinearLayout>
</layout>

效果图
android jetpack databinding的基本使用(java)

使用ObservableField来进行双向绑定

public class NameViewModel2 {


    private ObservableField<NameModel> nameModelObservableField;


    public NameViewModel2() {

        NameModel nameModel = new NameModel();
        nameModel.name = "zhang san";

        nameModelObservableField = new ObservableField<>();
        nameModelObservableField.set(nameModel);

    }


    public String getName() {

        return nameModelObservableField.get().name;
    }

    public void setName(String name) {

        nameModelObservableField.get().name = name;
    }

}

布局,main_tt_name2在这里不起作用,所以添加了button来获取值。

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

        <variable
            name="nameViewModel"
            type="cn.jn.mytest.observable.NameViewModel2" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">


        <EditText
            android:id="@+id/main_et_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@={nameViewModel.name}" />

        <TextView
            android:id="@+id/main_tt_name2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{nameViewModel.name}" />

        <Button
            android:id="@+id/main_but_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="获取名字" />

    </LinearLayout>
</layout>

效果图
android jetpack databinding的基本使用(java)
android jetpack databinding的基本使用(java)

在recycleview中使用databinding

item的布局文件

<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

        <variable
            name="sentence"
            type="cn.jn.mytest.entity.Sentence" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/sentence_tv_sentence"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{sentence.sentence}" />

        <TextView
            android:id="@+id/sentence_tv_sentence_ch"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{sentence.sentenceCH}" />


    </LinearLayout>
</layout>

适配器

public class SentenceAdapter extends RecyclerView.Adapter<SentenceAdapter.SentenceViewHolder> {

    private List<Sentence> sentenceList;


    public SentenceAdapter(List<Sentence> sentenceList) {
        this.sentenceList = sentenceList;
    }

    @NonNull
    @Override
    public SentenceViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        ItemSentenceBinding itemSentenceBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.item_sentence, parent, false);
        return new SentenceViewHolder(itemSentenceBinding);
    }

    @Override
    public void onBindViewHolder(@NonNull SentenceViewHolder holder, int position) {

        Sentence sentence = sentenceList.get(position);
        holder.itemSentenceBinding.setSentence(sentence);
    }

    @Override
    public int getItemCount() {
        return sentenceList.size();
    }

    public static class SentenceViewHolder extends RecyclerView.ViewHolder {

        ItemSentenceBinding itemSentenceBinding;

        public SentenceViewHolder(@NonNull ItemSentenceBinding itemView) {
            super(itemView.getRoot());
            this.itemSentenceBinding = itemView;
        }
    }
}

使用文章来源地址https://www.toymoban.com/news/detail-497967.html

        List<Sentence> sentenceList = new ArrayList<>();
        sentenceList.add(new Sentence("hello", "你好", 0));
        sentenceList.add(new Sentence("His trousers are the same as mine.", "他的裤子和我的一样。", 0));
        sentenceList.add(new Sentence("Let him not stand in the rain.", "让他不要站在雨中。", 0));

        RecyclerView main_rv_list = findViewById(R.id.main_rv_list);

        main_rv_list.setLayoutManager(new LinearLayoutManager(this));
        SentenceAdapter sentenceAdapter = new SentenceAdapter(sentenceList);
        main_rv_list.setAdapter(sentenceAdapter);

到了这里,关于android jetpack databinding的基本使用(java)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【Jetpack】DataBinding 架构组件 ④ ( 使用 @BindingAdapter 注解为布局组件绑定自定义逻辑 | 网络图片加载 | 本地图片加载 )

    博客源码 : https://download.csdn.net/download/han1202012/87701531 BindingAdapter 是 DataBinding 数据绑定技术 的组成部分 ; 借助 @BindingAdapter 注解 可以 将自定义逻辑 绑定到 DataBinding 布局中 ; 在 DataBinding 布局中 , 不只是机械性的显示内容 或者 拼接内容 , 还需要 进行更复杂的操作 ; 如 : 为 I

    2023年04月12日
    浏览(37)
  • 【Jetpack】DataBinding 架构组件 ⑥ ( RecyclerView 数据绑定 )

    在 RecyclerView 中 , 如果要使用 DataBinding 架构组件进行数据绑定 , 首先要 启用 DataBinding , 并 导入 RecyclerView 依赖 , 在 Module 模块下的 build.gradle 构建脚本 中 , 配置如下内容 : 要绑定的数据是 RecyclerView 条目的数据 , 因此需要 将条目布局设置为 DataBinding 布局 ; 创建 item.xml 布局后

    2023年04月25日
    浏览(34)
  • Jetpack业务架构—四件套(Lifecycle、ViewModel、LiveData、DataBinding)

    Jetpack 是一个由多个库组成的套件,可帮助开发者遵循最佳做法、减少样板代码并编写可在各种 Android 版本和设备中一致运行的代码,让开发者可将精力集中于真正重要的编码工作。 Android Jetpack组件的优势: Jetpack推出的主要目的是为了能够让开发者更加快速、方便以及高质

    2024年02月09日
    浏览(29)
  • Android Databinding 使用教程

    Android Databinding 是 Android Jetpack 的一部分,它允许你直接在 XML 布局文件中绑定 UI 组件到数据源。通过这种方式,你可以更简洁、更直观地更新 UI,而无需编写大量的 findViewById 和 setText/setImageResource 等代码。 启用 Databinding 在你的 app 模块的 build.gradle 文件中启用 Databinding: 定

    2024年03月28日
    浏览(27)
  • 【Android】DataBinding 最全使用解析

    DataBinding 是谷歌官方在2015谷歌I/O大会发布的一个数据绑定框架,是 MVVM 模式在 Android 上的一种实现,用于降低布局和逻辑的耦合性,使代码逻辑更加清晰。 DataBinding 能够省去我们一直以来的 findViewById() 步骤,大量减少 Activity 内的代码, DataBinding 也是 Android Jetpack 中非常重要

    2024年02月15日
    浏览(33)
  • 【Jetpack】DataBinding 架构组件 ⑤ ( 数据模型与视图双向绑定 | BaseObservable 实现双向绑定 | ObservableField 实现双向绑定 )

    在之前的博客中 , 将 数据模型 Model 中的 指定 Field 字段 绑定到 View 视图中的组件 , 在实际案例中 , 将 Student 类中的 String 类型的 name 字段绑定到了 布局文件中的 TextView 组件中 , 当 Student#name 字段发生了改变 , 对应的 TextView 组件中显示的内容也发生了相应的修改 ; 上述绑定方

    2023年04月21日
    浏览(45)
  • Jetpack Hilt 框架的基本使用

    Hilt 是一个功能强大、用法简单的依赖注入框架,于 2020 年加入到 Jetpack 家族中。它是 Android 团队联系了 Dagger2 团队,一起开发出来的一个专门面向 Android 的依赖注入框架。相比于 Dagger2,Hilt 最明显的特征就是简单,并且提供了 Android 专属的 API。 此部分以使用了 Java 17 的

    2024年02月07日
    浏览(22)
  • 如何合理使用 Jetpack 组件开发 Android 项目?

    Jetpack 是 Android 官方推出的一套开发库,其中包含众多的组件,可以让 Android 开发者更快更高效地开发应用程序。Jetpack 组件分为四大部分:架构、行为、UI 和基础组件。 下面详细阐述如何合理使用 Jetpack 组件开发 Android 项目。 在使用 Jetpack 组件之前,首先应熟悉几个常用的

    2024年02月02日
    浏览(34)
  • Android Jetpack Compose之RadioGroup的使用

    Android Jetpack Compose是一个现代化的UI工具包,帮助开发者以声明式的方式构建出美观且功能强大的Android应用。在本文中,我们将详细介绍其中的一个重要组件—— RadioGroup 。 一. RadioGroup简介 Jetpack Compose中并没有像传统View系统中那样直接提供 RadioGroup ,但我们可以很方便地通

    2024年02月06日
    浏览(40)
  • Android Jetpack Compose中使用字段验证的方法

    数据验证是创建健壮且用户友好的Android应用程序的关键部分。随着现代UI工具包Jetpack Compose的引入,处理字段验证变得更加高效和直观。在这篇文章中,我们将探讨如何在Android应用中使用Jetpack Compose进行字段验证。 字段验证是确保用户在各种输入字段中输入的数据符合特定

    2024年02月11日
    浏览(32)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包