简体   繁体   中英

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在此处输入图像描述

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM