我正在尝试用RecyclerView
填充一些数据到GridLayoutManager
:
GridLayoutManager layoutManager = new GridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
这将从左到右将数据填充到网格中。第一项将被放入左上角等地方。
但我正在开发的应用程序是专为RTL语言设计的,所以我需要从右到左填充它。
我试图将最后一个参数更改为true
。但它只是将RecyclerView
向下滚动。
同时为layoutDirection
设置RecyclerView
属性不起作用(不考虑我的min API是16并且为API17 +添加了此属性):
<android.support.v7.widget.RecyclerView
android:id="@+id/grid"
android:layoutDirection="rtl"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
如何使用RecyclerView
创建一个从左到右填充的网格?
创建一个扩展GridLayoutMAnager
的类,并覆盖isLayoutRTL()
方法,如下所示:
public class RtlGridLayoutManager extends GridLayoutManager {
public RtlGridLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public RtlGridLayoutManager(Context context, int spanCount) {
super(context, spanCount);
}
public RtlGridLayoutManager(Context context, int spanCount, int orientation, boolean reverseLayout) {
super(context, spanCount, orientation, reverseLayout);
}
@Override
protected boolean isLayoutRTL(){
return true;
}
}
有一种更好的方法
您可以以编程方式更改RecycleView的布局方向
workHourRecycler = view.findViewById(R.id.market_hours_recycler);
workHourRecycler.setLayoutManager(new GridLayoutManager(getContext(),4));
//Programtically set the direction
workHourRecycler.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
穆罕默德的回答是正确的,但你不需要创建一个新的类。你可以简单地覆盖isLayoutRTL方法。
GridLayoutManager lm = new GridLayoutManager(this, 2) {
@Override
protected boolean isLayoutRTL() {
return true;
}
};
从表面上看,当qazxsw poi给qazxsw poi时,GridLayoutManager应该是fill rows from right。通常,此方向将继承自getLayoutDirection()
容器。
但是,如果这不能按预期工作,或者您需要将其推送到API 16,或者您的某些设备执行RTL支持不良,您只需从github中提取ViewCompat.LAYOUT_DIRECTION_RTL
,并使用自定义管理器调整到您的喜好。
它可能足以扩展股票RecyclerView's
并覆盖GridLayoutManager
。
它非常简单,只是调用方法GridLayoutManager
as,
layoutChunk()