是否可以以编程方式为 Android 中的 RecyclerView 子项设置重力?

Loo*_*oii 5 android android-relativelayout android-recyclerview

我试图在 RecyclerView 中为孩子设置重力,但看起来 LayoutParams 没有重力方法。我尝试了以下方法:

RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(
                RecyclerView.LayoutParams.WRAP_CONTENT, RecyclerView.LayoutParams.WRAP_CONTENT);
Run Code Online (Sandbox Code Playgroud)

我还尝试了以下方法:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
Run Code Online (Sandbox Code Playgroud)

在这两种情况下都params.setMargin(int, int, int, int)可以正常工作并且边距设置正确。

我的 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"/>
Run Code Online (Sandbox Code Playgroud)

我的相对布局(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>
Run Code Online (Sandbox Code Playgroud)

我想要做的是params.setGravity(int)或任何其他使这成为可能的黑客。谢谢。

kri*_*son 0

我会将 包裹RelativeLayout在 a 中FrameLayoutandroid:width="match_parent"然后将重力设置为 的左/右FrameLayout