一个HorizontalScrollView中间嵌套ListView,当手指垂直滑动ListView的时候,它滚动,当手指水平滑动ListView和它外的部分HorizontalScrollView滚动。
布局代码
<?xml version="1.0" encoding="utf-8"?>
<com.cn.horizon.life.widgets.MyHorizonScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:scrollbars="horizontal">
<RelativeLayout
android:layout_width="1000dp"
android:layout_height="match_parent"
android:background="#CDCDCD"
android:paddingTop="80dp">
<com.cn.horizon.life.widgets.MyListView
android:id="@+id/lvList"
android:layout_width="400dp"
android:layout_height="390dp"
android:layout_alignParentLeft="true"
android:background="#ff0" />
</RelativeLayout>
</com.cn.horizon.life.widgets.MyHorizonScrollView>
MyScrollView代码如下
import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.HorizontalScrollView;
import android.widget.ScrollView;
public class MyHorizonScrollView extends HorizontalScrollView {
private int lastX = 0;
private int lastY = 0;
public MyHorizonScrollView(Context context) {
super(context);
}
public MyHorizonScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyHorizonScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public MyHorizonScrollView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
super.onInterceptTouchEvent(ev);
int x = (int) ev.getX();
int y = (int) ev.getY();
boolean intercept = false;
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
intercept = false;
break;
case MotionEvent.ACTION_MOVE:
int dx = x - lastX;
int dy = y - lastY;
if (Math.abs(dx) > Math.abs(dy)) {
intercept = true;
} else {
intercept = false;
}
break;
case MotionEvent.ACTION_UP:
intercept = false;
}
lastX = x;
lastY = y;
return intercept;
}
}