ScrollView只能有一个子控件

来源:互联网 发布:linux编译工具链 编辑:程序博客网 时间:2024/04/20 04:17
ScrollView只能添加一个子控件,如果添加了多个子控件,则会出现“ScrollView can host only one direct child”异常
解决办法:子控件外面再套一层LinearLayout,注意只能是Linearlayout,布局中不能出现RelativeLayout

scrollview内部组件android:layout_height="fill_parent"无效的解决办法
解决办法:
需要设置scrollview的fillViewport属性为"true"才能使其子组件可以扩展

在ViewPager 外面嵌套ScrollView 时,发现ViewPager中的元素显示不出来。
解决办法:
在ScrollView节点指定android:fillviewport="true"

ScrollView嵌套ListView,ListView不能完全正确的显示
解决办法:
1)自定义一个ListView,重写onMeasure方法
@Override  
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
    int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,  
            MeasureSpec.AT_MOST);  
    super.onMeasure(widthMeasureSpec, expandSpec);  
}
2)计算每个Item的高度
public void setListViewHeightBasedOnChildren(ListView listView) {

 

  // 获取ListView对应的Adapter

  ListAdapter listAdapter = listView.getAdapter();

  if (listAdapter == null) {

   return;

  }

  int totalHeight = 0;

  for (int i = 0; i < listAdapter.getCount(); i++) { // listAdapter.getCount()返回数据项的数目

   View listItem = listAdapter.getView(i, null, listView);

   listItem.measure(0, 0); // 计算子项View 的宽高

   totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度

  }

  ViewGroup.LayoutParams params = listView.getLayoutParams();

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

  // listView.getDividerHeight()获取子项间分隔符占用的高度

  // params.height最后得到整个ListView完整显示需要的高度

  listView.setLayoutParams(params);

 }

3)listview添加适配器后或者适配器加载数据后重新设置ListView高度

listView.setAdapter(adapter);  
new ListViewUtil().setListViewHeightBasedOnChildren(listView);  


0 0
原创粉丝点击