给ListView添一个父控件
<LinearLayout android:id="@+id/lstparent" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@+id/list" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:scrollbars="none"> </ListView> </LinearLayout>
在代码中,ListView有几行就设多高
/** * 设置listview父控件高度 start */ LinearLayout lstparent = (LinearLayout) findViewById(R.id.lstparent); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) lstparent.getLayoutParams(); params.height = listItem.size() * 3 * 37;// 因为这里的尺寸是像素,所以转成dp要*3 lstparent.setLayoutParams(params); /** * 设置listview父控件高度 end */
如果listView上方有控件的话,这样设置listView的高度,ScrollView会默认展示ListView的位置,上面的布局滚走了,所以,要给最上方的控件焦点
top.setFocusable(true);// 焦点给柱状图,防止页面默认展示scrollview的下办部分 top.setFocusableInTouchMode(true); top.requestFocus();
完成。
新发现一个作者写的,很好用:https://www.cnblogs.com/phj981805903/p/3230040.html