code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | /** * 设置ListView的高度 */ public static void setListViewHeightBasedOnChildren(ListView lv) { ListAdapter listAdapter = lv.getAdapter(); if (listAdapter == null ) { // pre-condition return ; } int totalHeight = 0; for ( int i = 0; i < listAdapter.getCount(); i++) { View listItem = listAdapter.getView(i, null , lv); listItem.measure(0, 0); totalHeight += listItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = lv.getLayoutParams(); params .height = totalHeight + (lv.getDividerHeight() * (listAdapter.getCount() - 1)); lv.setLayoutParams( params ); } |
ListView使用的时候一定要嵌套在 LinearLayout 中,因为其他的Layout(如RelativeLayout)没有重写onMeasure(),所以会在onMeasure()时抛出异常,导致重设高度失效。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <?xml version= "1.0" encoding= "utf-8" ?> <LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:app= "http://schemas.android.com/apk/res-auto" xmlns:tools= "http://schemas.android.com/tools" android:layout_width= "match_parent" android:layout_height= "match_parent" android:orientation= "vertical" tools:context= "com.jay.myappstudy.SvLvActivity" > <ScrollView android:id= "@+id/sv1" android:layout_width= "match_parent" android:layout_height= "match_parent" android:fillViewport= "true" > <LinearLayout android:layout_width= "match_parent" android:layout_height= "match_parent" > <ListView android:id= "@+id/lv1" android:layout_width= "match_parent" android:layout_height= "match_parent" /> </LinearLayout> </ScrollView> </LinearLayout> |
page code
1 2 3 4 5 6 7 8 9 10 11 | mlv1 = findViewById(R.id.lv1); ListViewAdapter adapter = new ListViewAdapter( this , mlv1,R.layout.fruit_item, data2); mlv1.setOnItemClickListener( new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { } }); mlv1.setAdapter(adapter); Utility.setListViewHeightBasedOnChildren(mlv1); |
分类:
Android
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
2018-03-07 (IOS可自动播放)使用bxslider做了一个切换图片跟随播放MP3的功能