Is it possible to set gravity programmatically for RecyclerView children in Android?

≡放荡痞女 提交于 2019-12-23 15:18:43

问题


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:


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
}



回答2:


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



来源:https://stackoverflow.com/questions/31101577/is-it-possible-to-set-gravity-programmatically-for-recyclerview-children-in-andr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!