我正在使用Android View绑定(在Android Studio 3.6上)。 我正在使用自动生成的类来为ViewHolder充气,例如
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
ViewHolderShowAllProductsBinding binding = ViewHolderShowAllProductsBinding.inflate(LayoutInflater.from(parent.getContext()));
return new MyViewHolder(binding);
}
MyViewHolder看起来像这样:
class MyViewHolder extends RecyclerView.ViewHolder {
public ViewHolderShowAllProductsBinding binding;
public MyViewHolder(ViewHolderShowAllProductsBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
}
在正常膨胀和findViewById的情况下,它会产生正确的结果:
由于我在有错误的地方使用ConstraintLayout和0dp,这使我相信View Binding膨胀不适用于ConstraintLayout的0dp。
我正确吗?解决方法是什么?
答案 0 :(得分:0)
在onCreateViewHolder方法中以这种方式使用DatabindingUtils
DataBindingUtil.inflate(LayoutInflater.from(viewGroup.getContext()),
R.layout.your_layout, viewGroup, false);
答案 1 :(得分:0)
我已经设法解决它,您应该尝试使用3个参数调用inflate
来传递父级。代替这个
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
ViewHolderShowAllProductsBinding binding = ViewHolderShowAllProductsBinding.inflate(LayoutInflater.from(parent.getContext()));
return new MyViewHolder(binding);
}
尝试这个:
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
ViewHolderShowAllProductsBinding binding = ViewHolderShowAllProductsBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false); // change this
return new MyViewHolder(binding);
}