码迷,mamicode.com
首页 > 移动开发 > 详细

android listview,GridView 和 ScrollView

时间:2015-04-16 12:29:04      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:android listview   gridview   relativelayout   linearlayout   measure   

前段时间 遇到 listview 和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);    
}

android listview,GridView 和 ScrollView

标签:android listview   gridview   relativelayout   linearlayout   measure   

原文地址:http://blog.csdn.net/hushaoxi/article/details/45072277

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!