Android Horizo​​ntalScrollView禁用滚动

Jim*_*Jim 6 android

我有一个长视图作为子视图的Horizo​​ntalScrollView,因此Horizo​​ntalScrollView是可滚动的,可以水平滚动它的子.有可能阻止吗?我不希望用户能够滚动视图.

小智 15

我的建议是使用OnTouchListener,例如:

onCreate方法中


HorziontalScrollView scrollView= (HorizontalScrollView)findViewById(R.id.scrollView);
scrollView.setOnTouchListener(new OnTouch());
Run Code Online (Sandbox Code Playgroud)

并有一个类:


private class OnTouch implements OnTouchListener
{
    @Override
    public boolean onTouch(View v, MotionEvent event) {
    return true;
    }
}
Run Code Online (Sandbox Code Playgroud)


Jim*_*Jim 2

好的,我找到了实现它的方法。

只需创建我自己的 Horizo​​ntalScrollView 并重写 onTouchEvent 方法

public class MyHSV extends HorizontalScrollView {

    public MyHSV(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    public MyHSV(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MyHSV(Context context) {
        super(context);
        init(context);
    }

    void init(Context context) {
        // remove the fading as the HSV looks better without it
        setHorizontalFadingEdgeEnabled(false);
        setVerticalFadingEdgeEnabled(false);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        // Do not allow touch events.
        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        // Do not allow touch events.
        return false;
    }

}
Run Code Online (Sandbox Code Playgroud)

然后在xml文件中

<pathToClass.MyHSV xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:scrollbars="none"
    android:id="@+id/myHSV>

</pathToClass.MyHSV>
Run Code Online (Sandbox Code Playgroud)