android - 如何使用 GridLayoutManager 自动调整 Recycler View 项目的高度和宽度
问题描述
我正在编写一个日历应用程序,所以我有 28-31 项要显示。
在最坏的情况下,我将有 4 行和 7 列,在最好的情况下,我将有 5 行和 7 列。
我正在使用GridLayoutManager
,所以:
recyclerView.layoutManager = GridLayoutManager(context, 7)
我没有使用任何代码来更改适配器中的代码,所以:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DayViewHolder {
var inflatedView = parent.inflate(R.layout.day_item_row)
return DayViewHolder(inflatedView)
}
override fun onBindViewHolder(holder: DayViewHolder, position: Int) {
val day = days[position]
}
我的 xml 参数RecyclerView
:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/calendarRecycler"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.65"
android:layout_margin="5dp"/>
对于该项目:
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/dayLinear"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/dayName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintDimensionRatio="1:1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:autoSizeTextType="uniform"
android:gravity="center"
android:text="5"/>
</androidx.constraintlayout.widget.ConstraintLayout>
制作物品正方形的最佳方法是什么,将全部自动安装RecyclerView
?
解决方案
为了在 RecyclerView 中有方形元素,请将项目布局(根视图)的父级设置为方形 ViewGroup。在这个例子中,我使用了 FrameLayout,但你可以对任何一个做同样的事情。(相对布局、线性布局等)
public class SquareFrameLayout extends FrameLayout {
public SquareFrameLayout(Context context) {
super(context);
}
public SquareFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public SquareFrameLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Set a square layout.
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
}
}
推荐阅读
- javascript - 如何将方法从一个组件传递到另一个组件并在 Vue.js 中单击时使用它?
- java - OpenWeatherMap API:遇到 NullPointerException
- activemq-artemis - 为什么在 Artemis 控制台中创建了许多具有 longValue 或 number 的队列?
- elasticsearch - 在 ElasticSearch 中的多个字段上进行单词和短语搜索
- flutter - Flutter Floating Action Button位置问题
- python - 问卷数据结构
- javascript - 是否可以通过一个提交按钮处理多个表单?
- ibm-cloud - IBM Cloud (Cloud Foundry) 上的 HTTP 400 与 Node.js an Express
- java - Junit 抛出初始化错误。找不到方法“com”
- python - 入门:如何创建服务器端应用程序来破译代码并采取行动?