我正在做一个GridView(非动态),它包含13个值,我想将它放在两列上,它看起来像:
这是我的代码:
ObservableCollection
我用<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="5dp"
card_view:cardUseCompatPadding="true" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_gravity="center"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tvCard"
android:text="A"
android:layout_marginRight="@dimen/_7sdp"
android:textSize="@dimen/_27sdp"
android:layout_centerVertical="true"
android:layout_toLeftOf="@+id/ivCard"
android:layout_toStartOf="@+id/ivCard" />
<ImageView
android:id="@+id/ivCard"
android:layout_width="@dimen/_20sdp"
android:layout_height="@dimen/_28sdp"
android:src="@mipmap/ic_launcher"
android:scaleType="centerCrop"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
为什么不把它放在中间?
Span
答案 0 :(得分:7)
答案 1 :(得分:0)
我遇到了同样的问题:我有一个带有两列和奇数个元素的GridLayout。最后一个元素必须居中。
我使用自定义SpanSizeLookup
并在最后一个元素上添加了一些边距来解决它:
在RecyclerView /活动中:
val layoutManager = GridLayoutManager(context, 2)
layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup()
{
override fun getSpanSize(position: Int): Int
{
return if (position == 0 || isLastRowAndShouldBeCentered(position)) 2 else 1
}
}
myRecyclerView.layoutManager = layoutManager
在适配器中:
override fun onCreateViewHolder(parent: ViewGroup): ViewHolder
{
// Save the width of the container
this.containerWidth = parent.measuredWidth
// Create your ViewHolder here
}
override fun onBindViewHolder(holder: ViewHolder, position: Int)
{
...
/**
* This margin will be exactly 1/4 of the container width.
* This way, the element will be displayed as follows :
* [ BLANK 1/4 SPACE ] [ ELEMENT 1/2 WIDTH ] [ BLANK 1/4 SPACE ]
*/
if (isLastRowAndShouldBeCentered(position))
{
val params = viewHolder.view.layoutParams as GridLayoutManager.LayoutParams
val marginSize = this.containerWidth / 4 // Re-use the container width here
params.leftMargin = marginSize
params.rightMargin = marginSize
viewHolder.view.layoutParams = params
}
}
很显然,isLastRowAndShouldBeCentered
是您要实现的(返回一个布尔值,指示我们是否在最后一个元素上,并且我们有奇数个元素)
希望它可以帮助某人!