ListView动态视图显示不全

ListView动态控制条数,总是显示不全,现在在网上找到解决方案,与大家分享

大概思路,重写ListView类的onMeasure(...)方法,xml布局使用自定义的HstListView类,代码如下:

package com.hst.taxmobile.common;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;

public class HstListView extends ListView {

	public HstListView(Context context) {
		// TODO Auto-generated method stub
		super(context);
	}

	public HstListView(Context context, AttributeSet attrs) {
		// TODO Auto-generated method stub
		super(context, attrs);
	}

	public HstListView(Context context, AttributeSet attrs, int defStyle) {
		// TODO Auto-generated method stub
		super(context, attrs, defStyle);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// TODO Auto-generated method stub
		int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,MeasureSpec.AT_MOST);
		super.onMeasure(widthMeasureSpec, expandSpec);
	}
}

页面设置:

    <com.hst.taxmobile.common.HstListView
	android:id="@+id/pmxx_listview"
	android:layout_width="match_parent"
	android:layout_height="wrap_content"
	android:divider="#eeeeee"
	android:dividerHeight="10dp"
	android:background="@drawable/shapes_rect_round" />

上面这种是通用的,有些可以使用以下方法计算出当前ListView的长度:

	/*
	 * 根据listView的child数量设置listView的高度
	 */
	public static 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();
		  }

		  ViewGroup.LayoutParams params = listView.getLayoutParams();

		  params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));

		  listView.setLayoutParams(params);
	}

猜你喜欢

转载自pyez1158.iteye.com/blog/2035590
今日推荐