自定义Horizo​​ntalScrollView管理 - 启用/禁用滚动

时间:2015-08-05 08:13:31

标签: android android-layout horizontalscrollview

我正在尝试同时进行垂直和水平滚动,但有些时候我不需要激活此水平滚动。

所以我想有一个自定义水平视图组件,我可以根据需要管理水平滚动。

所以我实现了这个自定义水平滚动类:

public class CustomHorizontalScroll extends ScrollView {

    private boolean enableScrolling = true;

    public boolean isEnableScrolling() {
        return enableScrolling;
    }

    public void setEnableScrolling(boolean enableScrolling) {
        this.enableScrolling = enableScrolling;
    }

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

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

    public CustomHorizontalScroll(Context context) {
        super(context);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {

        if (isEnableScrolling()) {
            return super.onInterceptTouchEvent(ev);
        } else {
            return false;
        }
    }
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (isEnableScrolling()) {
            return super.onTouchEvent(ev);
        } else {
            return false;
        }
    }
}

在我的活动中,我可以启用或禁用滚动:

horizontalScrollView = (CustomHorizontalScroll) findViewById(R.id.horizontal_scroll_view);
horizontalScrollView.setEnableScrolling(true); // try first to set as enable by default to see if it works

但是此时滚动总是被阻止,即使我在上面的例子中传递了'true'。

这里我的布局代码包含垂直和水平滚动:

<!-- Vertical scroll -->
    <ScrollView
        android:id="@+id/staffList_scrollview"
        android:layout_width="950dp"
        android:layout_height="555dp"
        android:layout_marginTop="10dp">

        <!-- Horizontal scroll -->
        <com.myPackage.CustomHorizontalScroll
            android:id="@+id/horizontal_scroll_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">
                ....
            </RelativeLayout>
       </com.myPackage.CustomHorizontalScroll>

</ScrollView>

这可能是我的问题?我希望能够禁用并启用此水平滚动。但目前使用此自定义水平类时,此滚动始终处于禁用状态,我可以将其启用。

1 个答案:

答案 0 :(得分:0)

我认为有两个问题。首先,扩展到ScrollView而不是Horizo​​ntalScrollView。

其次,为垂直滚动指定固定宽度。

<ScrollView
    android:id="@+id/staffList_scrollview"
    android:layout_width="950dp"
    android:layout_height="555dp"
    android:layout_marginTop="10dp">

如果你改变它应该有效

<ScrollView
    android:id="@+id/staffList_scrollview"
    android:layout_width="match_parent"
    android:layout_height="555dp"
    android:layout_marginTop="10dp">

测试这些变化并告诉我它是否有效。问候。

相关问题