android listview,GridView 和 ScrollView
if (listAdapter == null || listAdapter.getCount() == 0) { 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(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); listView.clearFocus();
这个里面有一个很重要的问题,在调用 listItem.measure(0, 0); 有些时候会报错,根本原因在于 listitem 的布局;最外面布局采用 LinearLayout,在调用listItem.measure(0, 0)时,其实根本是调用 LinearLayout.measure 方法;同样 RelativeLayout 布局也是一样,但是,调用RelativeLayout .measure 方法 会报错 。
解决办法:
1.listitem 布局最外层 用LinearLayout。
2. listitem 布局最外层 依然采用 RelativeLayout 布局,自定义RelativeLayout 并重写 onMeasure方法
@Override protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec){ int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); // Restrict the aspect ratio to 1:1, fitting within original specified dimensions int chosenDimension = Math.min(widthSize, heightSize); widthMeasureSpec = MeasureSpec.makeMeasureSpec(chosenDimension, MeasureSpec.AT_MOST); heightMeasureSpec = MeasureSpec.makeMeasureSpec(chosenDimension, MeasureSpec.AT_MOST); getLayoutParams().height = chosenDimension; getLayoutParams().width = chosenDimension; super.onMeasure(widthMeasureSpec, heightMeasureSpec); }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。