androidandroid-recyclerviewandroid-compound-view

How to set layout parameters for view added at RecycleView adaptor?


I am adding a Compound View on onCreateViewHolder for each data item of the RecycleView. I need to align to the right or the left according to data item value.

If i set the layout parameters for the view at that method, they are overridden by the values on the xml layout file.

The only solution i can come up with is having 2 different layouts files, but that unnecessary duplicates the files.

Any idea how to accomplish this by code?

Update: i try also at onBindViewHolder, the code below.

 @Override
 public void onBindViewHolder(ViewHolder holder, int position) {

    View v = holder.itemView;

    //to simplify i try to aling all to the rigth
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    params.addRule(RelativeLayout.ALIGN_PARENT_END); //this settins has effect if defined on the layout file
    v.setLayoutParams(params);
}

Solution

  • Found out. I assumed that holder.itemView was the Compound View i added. I needed to use findViewById to get the Compound View and set the parameters to that view. So, the solution was to find Compound View from the itemView like this:

    View v = holder.itemView.findViewById(android.R.id.content);
    

    Then apply the parameters to this view as posted in the question.