Android之视图绑定ViewBinding

视图绑定  |  Android 开发者  |  Android Developers

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)
}

在Kotlin中使用ViewModel-View Binding处理Fragment的视图绑定,可以简化UI和业务逻辑的分离。以下是基本步骤: 1. **添加依赖**:首先,在你的`build.gradle(Module)`文件中添加Kotlin View Binding的依赖: ```groovy implementation "androidx.appcompat:appcompat:1.4.0" kapt "androidx.annotation:annotationProcessor:$androidXAnnotationVersion" ``` 2. **创建ViewModel**:如果还没有,为你的Fragment创建对应的ViewModel。在ViewModel类中,你可以管理数据和状态。 3. **在Fragment中启用绑定**:在你的Fragment类里,通过`requireView()`方法获取布局资源ID,然后声明一个变量并初始化它: ```kotlin override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val binding = FragmentYourNameBinding.inflate(inflater, container, false) return binding.root } ``` 4. **绑定视图**:接下来,将数据绑定视图组件上。例如,如果你想把字符串赋值给一个TextView: ```kotlin binding.textViewYourTitle.text = viewModel.yourTitle ``` 5. **响应数据变化**:在ViewModel中,当你更新数据时,不需要手动通知UI,因为数据的变化会自动地反映在视图上。 6. **观察者模式**:如果你希望双向绑定,可以在ViewModel里使用LiveData或 MVVM库(如Hilt、Room-livedata-extension等),监听数据变化并自动更新视图。 记得在构建工具生成View Binding的注解处理器支持之后,运行`gradlew build`或`./gradlew assembleDebug`来同步生成binding相关的源码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值