ViewBinding 初探-在Activity和Adapter中使用

2023-05-16

升级android studio后(主要是gradle升级后),butterknife 不再被支持;

现在google主推ViewBinding 

一下就是我用ViewBinding 做的一个小demo,展示ViewBinding 的使用

一、build.gradle配置

        1、ViewBinding

android {
    ……
    buildFeatures {
        viewBinding = true
    }
}

        2、dependencies 相关配置

        

dependencies {
    ……

    //RecyclerView 列表
    implementation 'androidx.recyclerview:recyclerview:1.2.0-beta01'

}

二、界面展示

三、activity代码

        1、activity_main.xml  代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

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

        <EditText
            android:id="@+id/etName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#000000"
            android:textSize="18sp"
            android:hint="名称"/>

        <EditText
            android:id="@+id/etAge"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#000000"
            android:inputType="number"
            android:textSize="18sp"
            android:hint="年龄"/>

        <Button
            android:id="@+id/btnAdd"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="添加"/>

    </LinearLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:gravity="center|left"
        android:paddingLeft="20dp"
        android:background="#D9F8F5"
        android:textColor="#000000"
        android:textSize="18sp"
        android:text="数据列表-点击可删除"/>
    
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rvData"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

        2、MainActivity  代码

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import android.os.Bundle;

import com.xolo.myobjectbox.databinding.ActivityMainBinding;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    //系统依据 activity_main.xml 自动生成的 ActivityMainBinding 类,通过 ActivityMainBinding 可以获取对应的控件
    ActivityMainBinding mainBinding;

    private StudentAdapter studentAdapter;
    private List<StudentModel> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main); -需要注释掉
        //加载界面
        mainBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(mainBinding.getRoot());

        //添加StudentAdapter适配器
        list = new ArrayList<>();
        studentAdapter = new StudentAdapter(this, list, o -> {
            list.remove((int)o);
            studentAdapter.notifyDataSetChanged();
        });
        mainBinding.rvData.setLayoutManager(new GridLayoutManager(this, 1));
        mainBinding.rvData.setNestedScrollingEnabled(true);
        mainBinding.rvData.setAdapter(studentAdapter);

        //添加点击事件
        mainBinding.btnAdd.setOnClickListener(v -> {
            String name = mainBinding.etName.getText().toString();
            String age = mainBinding.etAge.getText().toString();

            list.add(0, new StudentModel(name, age));
            studentAdapter.notifyDataSetChanged();
        });

    }
    
}

四、adapter代码

        1、adapter_student.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="wrap_content"
    android:orientation="vertical"
    android:padding="5dp"
    android:background="#FFFFFF"
    android:layout_marginBottom="1dp"
    android:id="@+id/llClick">

    <TextView
        android:id="@+id/tvName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="name:"
        android:textColor="#000000"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/tvAge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="age:"
        android:textColor="#000000"
        android:textSize="18sp" />


</LinearLayout>

        2、StudentAdapter

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.xolo.myobjectbox.databinding.AdapterStudentBinding;

import java.util.List;

public class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.ViewHolder> {

    private Context context;
    private List<StudentModel> list;
    private ClickInterface clickInterface;

    public StudentAdapter(Context context, List<StudentModel> list, ClickInterface clickInterface) {
        this.context = context;
        this.list = list;
        this.clickInterface = clickInterface;
    }

    @NonNull
    @Override
    public StudentAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //界面设置
        AdapterStudentBinding studentBinding = AdapterStudentBinding.inflate(LayoutInflater.from(context), parent, false);
        return new ViewHolder(studentBinding);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onBindViewHolder(@NonNull StudentAdapter.ViewHolder holder, int position) {
        holder.studentBinding.tvName.setText("姓名:"+list.get(position).getName());
        holder.studentBinding.tvAge.setText("年龄:"+list.get(position).getAge());
        holder.studentBinding.llClick.setOnClickListener(v -> clickInterface.ClickOnThe(position));
    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {
        系统依据 activity_main.xml 自动生成的 AdapterStudentBinding 类,通过 ActivityMainBinding 可以获取对应的控件
        AdapterStudentBinding studentBinding;
        public ViewHolder(@NonNull AdapterStudentBinding itemView) {
            super(itemView.getRoot());
            studentBinding = itemView;
        }
    }
}

五、Interface代码

public interface ClickInterface {
    void ClickOnThe(Object o);
}

六、Model代码

public class StudentModel {

    private String name;
    private String age;

    public StudentModel() {
    }

    public StudentModel(String name, String age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

七、代码界面展示

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ViewBinding 初探-在Activity和Adapter中使用 的相关文章

  • Ubuntu 修改中文字体教程

    刚刚开始使用Ubuntu xff0c 在终端代码里可以看到奇奇怪怪丑陋的中文字体 xff0c 怎么换成更好看的中文字体呢 看了很多教程都是通过修改终端字体来实现 xff0c 但这样就不能使用自己想要的英文字体了 xff0c 比如我使用 So

随机推荐

  • STM32接口FSMC与FMC控制 XXROM

    FMC是STM32F429 439专有的 xff0c 因为驱动SDRAM时需要定时刷新 xff0c 而FSMC存在于F1和F4中我们常用的芯片中 他们的全称为 xff1a Flexible static memory controller
  • springcloud通过nacos整合seata遇到的问题

    1 配置完成后 xff0c 启动seata server服务器 xff0c 注册到nacos xff0c 启动client后访问接口 xff0c 报错如下 xff1a io seata common exception FrameworkE
  • mysql和redis双写一致性策略分析

    mysql和redis双写一致性策略分析 一 什么是双写一致性 当我们更新了mysql中的数据后也可以同时保证redis中的数据同步更新 xff1b 数据读取的流程 xff1a 1 读取redis 如果value 61 null 直接返回
  • js使用微信分享功能

    在使用微信分享 包括微信api里的其他方法 之前 xff0c 需要有一些准备 比如要准备 appId timestamp nonceStr signature 这四个数据 xff0c 只有在有这四个字段后 xff0c 我们才可以去使用微信的
  • the server send a disconnect packet/Start timer (TIMER_SHUTDOWN, 180).

    root 64 localhost Server rpm ivh xterm 215 5 el5 i386 rpm warning xterm 215 5 el5 i386 rpm Header V3 DSA signature NOKEY
  • IDEA和VSCode编辑器修改终端Terminal

    修改 Idea 终端 Terminal 为 GitBash 打开设置 xff08 快捷键 xff1a Ctrl 43 Alt 43 S xff09 xff0c 进入 Plugins 搜索栏搜索 Terminal xff0c 查看 Termi
  • 在PowerShell上创建并进入一个目录

    1 开始 运行 powershell 2 直接输入 xff0c 你想要把新建目录放在哪个盘下面 xff0c 我选的是d盘 xff0c 然后回车就会出现PS D gt 的字样 3 直接在后面输入new item xff08 新建目录 xff0
  • 13.5 JOIN语句

    13 5 JOIN语句 MySQL中的JOIN语句为各种连接查询 主要用来连接MySQL中的两个表或多个表 实现两个表或多个表之间的连接查询 13 5 1 INNER JOIN语句 INNER JOIN语句也叫作内连接语句 能够返回与连接条
  • 如何在Windows上使用cmd递归删除文件或文件夹?批量删除指定大小的图片文件

    如何在Windows上使用cmd递归删除文件或文件夹 xff1f span class token keyword for span r R span class token keyword in span span class token
  • QT中编译MQTT模块

    1 下载MQTT源码 下载地址 xff1a https github com qt qtmqtt https github com qt qtmqtt 不要下载点开链接后默认出现的版本 xff0c 选择和QT对应版本的源码 2 解压源码 u
  • python爬虫---网易云音乐下载

    python爬虫爬取网易云音乐 1 实现功能2 具体实现1 搜索部分2 下载歌曲1 再次获取信息2 下载 3 结语 Github完整代码获取 xff1a https github com Lian Zekun python spilder
  • httpd功能特性及配置介绍(一)

    一次web请求的基本过程 xff1a 建立连接 gt 接受请求 gt 处理请求 gt 访问资源 gt 构建响应 gt 发送响应 gt 记录日志 web服务器的输入 输出结构 单线程I O结构 多线程I O结构 复用的I O结构 复用的多线程
  • 不准再说linux丑,Ubuntu20.04+kde美化,动态桌面,软件安装

    ubuntu20 04美化教程 xff0c 附加动态壁纸教程 安装ubuntu kde ubuntu官网下载好最新发行版ubuntu20 04 xff0c 制作启动盘以最小安装 xff0c 安装系统 xff0c 然后替换 etc apt s
  • 优化器(Optimizer)介绍

    Gradient Descent xff08 Batch Gradient Descent xff0c BGD xff09 梯度下降法是最原始 xff0c 也是最基础的算法 它将所有的数据集都载入 xff0c 计算它们所有的梯度 xff0c
  • 解决Manjaro系统安装MindMaster思维导图用不了(登录不了的问题)的问题,以及代替的方案

    解决Manjaro系统安装MindMaster思维导图用不了 xff08 登录不了的问题 xff09 的问题 xff0c 以及代替的方案 1 xff0e 罗嗦废话 xff08 可无视 xff09 xff12 xff0e 面向搜索引擎探寻解决
  • Ubuntu下使用date显示毫秒级

    echo e 34 date 43 T 10 date 43 N 1000000 34 14 17 30 996 如果不加以10进制显示 96 96 96 10 96 96 96 就会在达到999毫秒后失败 echo e 34 date 4
  • IntelliJ IDEA 目录技巧

    IntelliJ IDEA的Web应用的目录结构 目录图 xff1a 目录解释 xff1a 开发目录 目录名称 描述 Test 工程名称 lib Jar包的存放目录 src 源文件也就是文件 类 xff0c 资源文件 存放的目录 test
  • 如何在win10系统上改装高仿MAC主题桌面

    一 前言 作为一名学生党 xff0c 一直很喜欢MacBook的简洁界面以及它的细节动画效果 xff0c 但多年习惯使用了windows系统 xff0c 且部分软件在MAC OS系统不能很好兼容 xff0c 再加上经费不足 xff0c 于是
  • CP 测试setup 总结

    在半导体行业的芯片测试中 xff0c CP测试往往会在setup搭建测试环境的时候会出现一些异常导致无法保障连接良好 xff0c 阻碍后续测试项的进行 xff1b 简单对多site SETUP验证思维的一个总结分享 xff1b 通常CP的D
  • ViewBinding 初探-在Activity和Adapter中使用

    升级android studio后 xff08 主要是gradle升级后 xff09 xff0c butterknife 不再被支持 xff1b 现在google主推ViewBinding 一下就是我用ViewBinding 做的一个小de