0

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);
}
MiguelSlv
  • 14,067
  • 15
  • 102
  • 169

2 Answers2

1

Anything done according to the data of the data item should be done in onBindViewHolder, not in onCreateViewHolder. At creation time you should only set things that will be correct regardless of the actual data bound, or the position it is bound at. All the data and position specific settings get done in onBindViewHolder.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
0

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.

MiguelSlv
  • 14,067
  • 15
  • 102
  • 169