在xml布局中,将listview嵌套到scrollview中,两者之间的滑动事件会起冲突,并且listview的高度度也会受到影响。
这里我找到了两种解决方案:
1.动态改变listview的长度,但是listview不能滑动
(1)继承listview重写onMeasure事件
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); } (2)动态改变listview控件的高度,获取listview的layoutparams和item的layoutparams,然后来改变其高度。 这个方法有一定的缺陷,数据比较大的话会影响到软件的运行速度,不太推荐。 private void changeListView(ListView listView,LinearLayout item){ RelativeLayout.LayoutParams params= (RelativeLayout.LayoutParams) listView.getLayoutParams(); RelativeLayout.LayoutParams itemParams=(RelativeLayout.LayoutParams) item.getLayoutParams(); params.height= itemParams.height*10; listView.setLayoutParams(params); }
2.根据触碰事件来改变listview和scollview的滑动:这种方法的话listview和scrollview是都可以滑动的。
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ListView;
import android.widget.ScrollView;
/**
* Author:Locio liu
* Created by Administrator on 2016/1/21.
* 可以在scrollview中滑动的listView 固定
*/
public class NestListView extends ListView {
//看情况可以定义为其他滑动的控件
public ScrollView parentScrollView;
public NestListView(Context context) {
super(context);
}
public NestListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NestListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
//根据listView获得的事件来
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
//当手指触到listview的时候,让父ScrollView交出ontouch权限,也就是让父scrollview 停住不能滚动
toParentScrollSlide(false);
Log.i("hint", "onInterceptTouchEvent ACTION_DOWN");
case MotionEvent.ACTION_MOVE://滑动事件
Log.i("hint","onInterceptTouchEvent ACTION_MOVE");
break;
case MotionEvent.ACTION_UP://抬手
Log.i("hint","onInterceptTouchEvent ACTION_UP");
case MotionEvent.ACTION_CANCEL:
//当手指松开时,让父ScrollView重新拿到onTouch权限
Log.i("hint","onInterceptTouchEvent ACTION_CANCEL");
toParentScrollSlide(true);
break;
default:
break;
}
return super.onInterceptTouchEvent(ev);
}
/**
* 是否把滚动事件交给父scrollview
*/
private void toParentScrollSlide(boolean flag) {
//这里的parentScrollView就是listView的布局控件
parentScrollView.requestDisallowInterceptTouchEvent(!flag);
}
}
附加:如果只是在scrollview中只有listview和其他的一个整体布局的话,可以调用listview的addheaderview事件。
View header = LayoutInflater.from(getContext()).inflate(R.layout.Test_layout, testList, false);
testList.addHeaderView(header);
附带:androidStudio项目下载链接:http://download.csdn.net/detail/u013674767/9413037
Eclipse项目下载链接:http://download.csdn.net/detail/u013674767/9413063
http://blog.csdn.net/u013674767/article/details/50554934