javaandroidandroid-recyclerviewgravitycardview

How to set cardView Gravity in RecyclerView Programatically


I'm trying here to set the layout gravity of certain elements in recycler view to RIGHT so i did this in the recycler view adapter

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

    Message message = messagesList.get(position);
    if (message.getSenderId().equals(auth.getCurrentUser().getUid()))
    {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.CENTER_IN_PARENT);
        holder.messageCv.setLayoutParams(params);
        holder.messageCv.setCardBackgroundColor(context.getResources().getColor(R.color.green));
        holder.senderTv.setTextColor(context.getResources().getColor(R.color.white));
        holder.messageCntnt.setTextColor(context.getResources().getColor(R.color.white));
    }
    holder.senderTv.setText(message.getSender());
    holder.messageCntnt.setText(message.getMessage());

}

But it didn't works

the recycler view looks like this enter image description here


Solution

  • Why did you use RelateiveLayout.LayoutParams? By the documentation:

    CardView extends FrameLayout https://developer.android.com/reference/androidx/cardview/widget/CardView

    So you should use FrameLayout.LayoutParams

    It has gravity field. I believe you can use this one. https://developer.android.com/reference/android/widget/FrameLayout.LayoutParams#gravity

    But it's not a best approach to set it programatically, better just to add the attribute to layout xml.