Android RecyclerView外部下拉框及EditText仅点击后显示问题求解
问题核心原因
布局参数配置存在冲突,导致控件无法正常完成测量渲染,才会出现默认隐藏、点击/输入才显示、滚动后再次隐藏的异常表现。
修复方案
1. 调整根布局与RecyclerView容器参数(优先方案,无需修改适配器逻辑)
你当前使用垂直LinearLayout作为根布局,存在两处致命参数错误:
- 根LinearLayout的
layout_height设为wrap_content,作为Activity的根布局必须设置为match_parent才能正常占满屏幕空间 - 包裹RecyclerView的RelativeLayout的
layout_height设为match_parent,在垂直LinearLayout中会占满所有剩余屏幕高度,挤压覆盖顶部下拉框和底部EditText的显示区域,同时引发RecyclerView绘制逻辑异常
修改后的完整布局代码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:theme="@style/Theme.MaterialComponents"> <com.google.android.material.textfield.TextInputLayout android:id="@+id/weekDropdown" style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu" android:hint="Select Week" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="32dp" android:layout_marginEnd="32dp" android:layout_marginTop="5dp" android:layout_marginBottom="5dp" app:startIconDrawable="@drawable/ic_round_calendar_today_24"> <AutoCompleteTextView android:id="@+id/weekSelected" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="none" android:padding="14dp" android:textSize="16sp"/> </com.google.android.material.textfield.TextInputLayout> <RelativeLayout xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" tools:context=".PickemPicksheetActivity"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent"/> </RelativeLayout> <EditText android:id="@+id/tp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="@string/lbl_tp" android:inputType="number" android:layout_gravity="center" android:textAlignment="center" android:minHeight="48dp" android:layout_marginBottom="10dp" android:maxLength="3" android:textColor="@color/black" /> </LinearLayout>
同时需修改RecyclerView子项布局中FrameLayout的layout_height参数,从match_parent改为wrap_content,避免单屏仅能显示一个游戏条目。
2. 可选方案:将控件作为RecyclerView头尾布局
如果需要将下拉框、EditText纳入列表滚动流,可通过多视图类型实现,不会重复渲染:
- 重写适配器
getItemViewType方法,区分头布局(下拉框)、游戏条目、底布局(EditText)三种类型 - 重写
getItemCount方法,返回值改为「游戏列表长度 + 2」 - 在
onCreateViewHolder中根据视图类型加载对应布局,onBindViewHolder中按位置绑定对应数据即可
内容的提问来源于stack exchange,提问作者Learn2Code
相关产品推荐
相关产品推荐

