Constraint Layout 0dp does not work on Android View Binding

Viewed 428

I am using the Android View Binding (on Android Studio 3.6). I am using the auto-generated Classes to inflate the ViewHolder, like

public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    ViewHolderShowAllProductsBinding binding = ViewHolderShowAllProductsBinding.inflate(LayoutInflater.from(parent.getContext()));
    return new MyViewHolder(binding);
}

And the MyViewHolder looks like this:

class MyViewHolder extends RecyclerView.ViewHolder {
    public ViewHolderShowAllProductsBinding binding;

    public MyViewHolder(ViewHolderShowAllProductsBinding binding) {
        super(binding.getRoot());
        this.binding = binding;
    }
}

But this produces UI errors like so: Ui error due to Android binding

When, with normal inflation and findViewById, it produces the correct results: Correct Ui with findViewById apoach

Since I am using ConstraintLayout and 0dp in the places where there are errors, this leads me to believe that View Binding inflation does not work properly with ConstraintLayout's 0dp.

Am I correct? What is the workaround?

2 Answers

Use DatabindingUtils this way at the onCreateViewHolder method

DataBindingUtil.inflate(LayoutInflater.from(viewGroup.getContext()),
                    R.layout.your_layout, viewGroup, false);

I've just managed to solve it, you should try to call inflate with 3 parameters to pass parent. Instead of this

public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    ViewHolderShowAllProductsBinding binding = ViewHolderShowAllProductsBinding.inflate(LayoutInflater.from(parent.getContext()));
    return new MyViewHolder(binding);
}

try this one:

public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    ViewHolderShowAllProductsBinding binding = ViewHolderShowAllProductsBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false); // change this
    return new MyViewHolder(binding);
}
Related