ScrollView和ListView的滑动冲突解决

重写ListView

@Override
 public boolean dispatchTouchEvent(MotionEvent ev) {
  //设置不拦截
  getParent().requestDisallowInterceptTouchEvent(true);
  return super.dispatchTouchEvent(ev);
 }
 
 @Override
 public boolean onInterceptTouchEvent(MotionEvent ev) {
  
  return super.onInterceptTouchEvent(ev);
 }
 
 @Override
 public boolean onTouchEvent(MotionEvent ev) {
  
  return super.onTouchEvent(ev);
 }
 
 @Override
 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  
 // heightMeasureSpec=MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE>>2, MeasureSpec.AT_MOST);
  super.onMeasure(widthMeasureSpec, heightMeasureSpec);
 }

根据listview的数据来计算他的应得的高度,设置高度

public void setListViewHeightBasedOnChildren(ListView listView) {
  @SuppressWarnings("unchecked")
  ArrayAdapter listAdapter = (ArrayAdapter) listView.getAdapter();
        if (listAdapter == null) {
            return;
        }      
        int totalHeight = 0;
       
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            if(listItem != null){
                listItem.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
                listItem.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
                totalHeight += listItem.getMeasuredHeight();
            }
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1))
                + listView.getPaddingTop() + listView.getPaddingBottom();
        int h = getWindowManager().getDefaultDisplay().getHeight();
        if(params.height > h/2){
         params.height = h/2;
        }
        listView.setLayoutParams(params);
    }

你可能感兴趣的:(学习)