xxt*_*axx 14 android google-maps adapter android-adapter android-recyclerview
我正在使用RecyclerView.我使用循环器视图来显示模型类的详细信息.
//My model class
MyModel {
String name;
Double latitude;
Double longitude;
Boolean isOnline;
...
}
Run Code Online (Sandbox Code Playgroud)
由于某些值可能不存在,我使用RecyclerView和自定义视图类型(一个代表我的模型的每个值).
//Inside my custom adapter
public void setModel(T model) {
//Reset values
itemCount = 0;
deviceOfflineViewPosition = -1;
mapViewPosition = -1;
//If device is offline, add device offline item
if (device.isOnline() == null || !device.isOnline()) {
deviceOfflineViewPosition = itemCount;
itemCount++;
}
//Add additional items if necessary
...
//Always add the map as the last item
mapViewPosition = itemCount;
itemCount++;
notifyDataSetChanged();
}
@Override
public int getItemViewType(int position) {
if (position == deviceOfflineViewPosition) {
return ITEM_VIEW_TYPE_OFFLINE;
} else if (position == mapViewPosition) {
return ITEM_VIEW_TYPE_MAP;
} else if (...) {
//Check for other view types
}
}
Run Code Online (Sandbox Code Playgroud)
使用RecyclerView,我可以在运行时轻松确定哪些值可用,并将相应的项添加到RecyclerView数据源.我简化了代码,但我的模型有更多的值,我有更多的视图类型.
RecyclerView中的最后一项始终是地图,并且始终存在.即使我的模型中根本没有任何价值,也至少会有一个项目,即地图.
问题:如何让RecyclerView中的最后一项填充屏幕上的剩余空间并且还有最小高度.尺寸应该是更大的价值:剩余空间或最小高度.例如:
在布置完最后一项之后,您可以在RecyclerView中找到剩余空间,并将剩余空间添加到最后一项的空间中minHeight。
val isLastItem = getItemCount() - 1 == position
if (isLastItem) {
val lastItemView = holder.itemView
lastItemView.doOnLayout {
val recyclerViewHeight = recyclerView.height
val lastItemBottom = lastItemView.bottom
val heightDifference = recyclerViewHeight - lastItemBottom
if (heightDifference > 0) {
lastItemView.minimumHeight = lastItemView.height + heightDifference
}
}
}
Run Code Online (Sandbox Code Playgroud)
使用onBindHolder检查项目是否为最后一个项目getItemCount() - 1 == position。如果是最后一项,则通过在lastItem bottom减去recyclerView height来找到高度差(getBottom()为您提供相对于其父视图的视图的最底像素。在这种情况下,我们的父是RecyclerView)。
如果差异大于0,则将其添加到最后一个视图的当前高度并将其设置为minHeight。我们将其设置为,minHeight而不是直接设置为height支持最后一个视图的动态内容更改。
注意:这段代码是Kotlin,而doOnLayout函数来自Android KTx。同样,您的RecyclerView身高也应match_parent如此(我想这很明显)。
| 归档时间: |
|
| 查看次数: |
2158 次 |
| 最近记录: |