解决Listview 在ScrollView中显示不全的问题

一开始在采用网上搜索的方法:

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();  
 }    
  ViewGroup.LayoutParams params = listView.getLayoutParams();          
  params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));  
  listView.setLayoutParams(params);
}

先给listView设置adapter,然后再采用上图的方法,这样就把条目显示出来了。

但是后期再运用的时候出现了问题,就是条目里面的高度不确定,文字的行数是1行或者两行不能写死,效果如下:

Paste_Image.png

原先的方法只能用于固定高度的条目,而不能用于不确定高度的条目。
经同事指点,用下面的自定义listView,代码如下:

public class MyListView extends ListView {   
public MyListView(Context context, AttributeSet attrs, int defStyle) {           
   super(context, attrs, defStyle);   
}   
public MyListView(Context context, AttributeSet attrs) {         
   super(context, attrs);  
 }   
public MyListView(Context context) {     
    super(context);  
 }   
@Override    
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {            
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,MeasureSpec.AT_MOST); 
super.onMeasure(widthMeasureSpec, expandSpec);   
}
}

这样不固定的条目就能展示了。

小提示: 在设置listView的距离屏幕间距的时候,不要在listview的XML里面设置,而是在条目里面的XML里面设置。
这是为了后期的扩展,有可能添加点击效果,一般都是在条目XML里面设置background,如果在listView里设置间距的话,点击的效果就会空出两个间隔的白边。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容