Is it possible to set gravity programmatically for

2019-06-24 02:31发布

问题:

I'm trying to set gravity for children in RecyclerView, but it looks like the LayoutParams does not have a gravity method. I have tried the following:

RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(
                RecyclerView.LayoutParams.WRAP_CONTENT, RecyclerView.LayoutParams.WRAP_CONTENT);

I have also tried the following:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

In both cases params.setMargin(int, int, int, int) works just fine and the margin is set correctly.

My RecyclerView:

<android.support.v7.widget.RecyclerView
    android:id="@+id/messages_list_view"
    android:scrollbars="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/toolbar"
    android:layout_marginTop="20dp"/>

My RelativeLayout (child of RecyclerView):

<RelativeLayout
android:id="@+id/message_text_wrapper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:background="@drawable/chat_bubble"
android:layout_margin="16dp"
android:padding="10dp"
xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:id="@+id/message_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:textColor="@android:color/primary_text_light"
        android:textSize="18sp"
        />

</RelativeLayout>

What I want to be able to do is params.setGravity(int) or any other hack that makes this possible. Thanks.

回答1:

I would wrap the RelativeLayout in a FrameLayout with android:width="match_parent" and then set the gravity left/right on the FrameLayout.



回答2:

Wrap your item view inside a FrameLayout, make sure its layout_width is set to match_parent.

Give your layout which you wrapped in the FrameLayout an id and connect it to your ViewHolder. (I think you've already done this with @+id/message_text_wrapper)

Then in onBindViewHolder do this:

FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) holder.yourLayout.getLayoutParams()
if (condition) {
    params.gravity = Gravity.END // or Gravity.RIGHT
} else {
    params.gravity = Gravity.START // or Gravity.LEFT
}