ViewBinding——Android之视图绑定

news/2024/5/20 5:26:18 标签: android, kotlin, ui, gradle

高版本的gradle不再支持 kotlin-android-extensions插件,因此view的绑定方式也有所改变。

1.启用视图绑定

android {
        ...
        viewBinding {
            enabled = true
        }
    }

如果想在生成绑定类时忽略某个布局文件,请将 tools:viewBindingIgnore="true" 属性添加到相应布局文件的根视图中:

<LinearLayout
        ...
    tools:viewBindingIgnore="true" >
        ...
</LinearLayout>
    

2.在 Activity 中使用视图绑定

如需设置绑定类的实例以供 Activity 使用,请在 Activity 的 onCreate() 方法中执行以下步骤:

  1. 调用生成的绑定类中包含的静态 inflate() 方法。此操作会创建该绑定类的实例以供 Activity 使用。
  2. 通过调用 getRoot() 方法或使用 Kotlin 属性语法获取对根视图的引用。
  3. 将根视图传递到 setContentView(),使其成为屏幕上的活动视图。
 private lateinit var binding: ResultProfileBinding
 
    override fun onCreate(savedInstanceState: Bundle) {
        super.onCreate(savedInstanceState)
        binding = ResultProfileBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
    }

3.在 Fragment中使用视图绑定

如需设置绑定类的实例以供 Fragment 使用,请在 Fragment 的 onCreateView() 方法中执行以下步骤:

  1. 调用生成的绑定类中包含的静态 inflate() 方法。此操作会创建该绑定类的实例以供 Fragment 使用。
  2. 通过调用 getRoot() 方法或使用 Kotlin 属性语法获取对根视图的引用。
  3. 从 onCreateView() 方法返回根视图,使其成为屏幕上的活动视图。
    private var _binding: ResultProfileBinding? = null
    private val binding get() = _binding!!
 
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = ResultProfileBinding.inflate(inflater, container, false)
        return binding.root
    }
 
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

4.自定义Dialog中使用

public class MyDialog extends Dialog {
 
    protected View mView;
    protected DialogBottomBinding mBinding;
    
    public MyDialog(@NonNull Context context, @StyleRes int themeResId) {
        super(context, themeResId);
 
        //原来的写法
        // mView = View.inflate(getContext(), getLayoutId(), null);
 
        //使用ViewBinding的写法
        mBinding = DialogBottomBinding.inflate(getLayoutInflater());
        mView = mBinding.getRoot();
        
        setContentView(mView);
    }
}

5.在自定义View中使用

// 自定义view
public class MyLinearLayout extends LinearLayout {
    public MyLinearLayout(Context context) {
        this(context, null);
    }
 
    public MyLinearLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }
 
    public MyLinearLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
 
        // 正常添加布局(亲测有效)
        ViewMyLayoutBinding binding = LibPlateformLayoutBinding.inflate(LayoutInflater.from(getContext()), this, true);
 
        // 方法二:
        // val root = View.inflate(context, R.layout.widget_core, this)
        // binding = WidgetCoreBinding.bind(root)
 
        // 针对根标签为merge
        ViewMyLayoutMergeBinding binding = ViewMyLayoutMergeBinding.inflate(LayoutInflater.from(getContext()), this);
    }
 
}

6.在RecyclerView的Adapter中使用

class StudentAdapter(private val context: Context,
                     private val list: List<AddressInfo>) : RecyclerView.Adapter<ItemViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
        val studentBinding = ItemAddressBinding.inflate(LayoutInflater.from(
            context), parent, false)
        return ItemViewHolder(studentBinding)
    }
 
    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
        holder.itemBinding.tvName.text = "姓名:" + list[position].name
    }
 
    override fun getItemCount(): Int {
        return list.size
    }
 
    inner class ItemViewHolder(var itemBinding: ItemAddressBinding) : RecyclerView.ViewHolder(
        itemBinding.root)
}

以上是各场景使用viewBinding的方式,基本可以满足大家的开发需求,如有其他场景的可以在评论区留言讨论。


http://www.niftyadmin.cn/n/5046963.html

相关文章

注入常考面试题总结

1.如何突破注入时字符被转义&#xff1f; 宽字符注入、hex 编码绕过&#xff08;尝试利用 ANSI 字符代码变体来达到目的 比如 " 号对应 chr(34) 是否成功取决于他本身程序是否也做了过滤.&#xff09; Chr(34)&#xff0c;由 ASCII 码生成字符&#xff0c;34 就是双引号…

map的一些测试-string键的查找

主要区别在于声明map的时候多了一个less<> #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> #include <map> #include <chrono> using namespace std; class spender { public:spender(string strfun) :strfun(strfun…

k8s1.19使用ceph14

一、静态 pv (rbd)方式 1、所有k8s节点安装依赖组件 注意:安装ceph-common软件包推荐使用软件包源与Ceph集群源相同,软件版本一致。 cat > /etc/yum.repos.d/ceph.repo << EOF [ceph] name=ceph baseurl=http://mirrors.aliyun.com/ceph/rpm-nautilus/el7/x86_…

升级iOS17后可以降级吗?iOS17退回iOS16方法教程分享

iOS 17已上线几天&#xff0c;从网上用户的反馈和媒体机构的报告来看&#xff0c;iOS17系统对旧机型来说并不友好&#xff0c;除了电池续航下降以外&#xff0c;占用大量储存空间&#xff0c;BUG也不少。 苹果于 9 月 7 日发布了 iOS 16.6.1 版本&#xff0c;如果升级iOS17后发…

深入了解函数调用的执行过程

函数调用是编程中常见的操作&#xff0c;它允许我们将代码模块化&#xff0c;并在需要时多次重复使用。在本文中&#xff0c;我们将深入了解函数调用的执行过程&#xff0c;包括函数和函数栈的基本概念&#xff0c;最后通过多个示例来说明函数如何被调用和执行。 函数调用的执…

第 364 场 LeetCode 周赛题解

A 最大二进制奇数 降序排序字符串&#xff0c;然后将最后一个 1 与最后一位交换 class Solution { public:string maximumOddBinaryNumber(string s) {sort(s.begin(), s.end(), greater<>());for (int i s.size() - 1;; i--)if (s[i] 1) {swap(s[i], s.back());break;…

寻找单身狗

在一个数组中仅出现一次&#xff0c;其他数均出现两次&#xff0c;这个出现一次的数就被称为“单身狗“。 一.一个单身狗 我们知道异或运算操作符 ^ &#xff0c;它的特点是对应二进制位相同为 0&#xff0c;相异为 1。 由此我们容易知道两个相同的数,进行异或运算得到的结果…

Django框架介绍和安装

Django框架介绍和安装 组件&#xff1a; 基本配置文件/路由器 模型层&#xff08;M&#xff09;/模板层&#xff08;T&#xff09;/视图层&#xff08;v&#xff09; Cookie和Seesion 分页及发邮件 Admin管理后台 init.py:Python包的初始化文件 wsgi.py:WEB服务网关的配…