Android 关于在ScrollView中加上一个ListView,ListView内容显示不完全(总是显示第一项)的问题的两种简单的解决方案
是这样的哈:
有这样一个需求:
1.显示一个界面,界面上有一个列表(ListView),列表上面有一个可以滚动的海报。
2.要求在ListView滚动的过程中,ListView上面的海报也可以跟着ListView滚动。
我们的一般解决方案:
1.使用ScrollView嵌套这一个ListView。
对,这样的布局本身是没哟什么问题的。但是问题来了,当你运行你的界面的时候,突然发现,你的列表中明明有好多项,但是为什么只显示一项呢?仔细检查你会发现,不是列表只显示一项,而是其它的项被布局本身遮住了。
怎么办呢?下面将给出两种相对简单的解决方案:
第一种:禁用ListView的滚动(Scroll)。
第二种:计算ListView中每一项的高度,然后根据每一项的高度“乘以”项数,计算出ListView的总高度。
下面给出第一种方法的代码展示:
import android.widget.ListView; public class MyListView extends ListView{ public MyListView(android.content.Context context,android.util.AttributeSet attrs){ super(context, attrs); } /** * 设置不滚动 */ public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); } }
以下是第二种方法的的代码:
/**动态改变listView的高度*/ public void setListViewHeightBasedOnChildren(ListView listView) { ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { return; } int totalHeight = 0; for (int i = 0; i < listAdapter.getCount(); i++) { View listItem = listAdapter.getView(i, null, listView); listItem.measure(0, 0); totalHeight += listItem.getMeasuredHeight(); // totalHeight += 80; } ViewGroup.LayoutParams params = listView.getLayoutParams(); // params.height = 80 * (listAdapter.getCount() - 1); // params.height = 80 * (listAdapter.getCount()); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); ((MarginLayoutParams) params).setMargins(0, 0, 0, 0); listView.setLayoutParams(params); }
到此为止问题结束。如果哪位朋友有更好的解决办法,别忘了提出来分享一下哈。
分类:
Android
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库