溫馨提示×

如何自定義Android View以支持垂直滾動

小樊
90
2024-08-20 10:59:32
欄目: 編程語言

要自定義一個支持垂直滾動的 Android View,你可以繼承自 ViewGroup 或者 View,并實現自己的滾動邏輯。以下是一個簡單的示例代碼:

public class CustomScrollView extends ViewGroup {

    private int mScrollY;

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

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        int childTop = 0;
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            child.layout(0, childTop, getWidth(), childTop + child.getMeasuredHeight());
            childTop += child.getMeasuredHeight();
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);

        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            child.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
                    MeasureSpec.makeMeasureSpec(height, MeasureSpec.UNSPECIFIED));
        }

        setMeasuredDimension(width, height);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mScrollY = (int) event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                int deltaY = (int) (event.getY() - mScrollY);
                scrollBy(0, -deltaY);
                mScrollY = (int) event.getY();
                break;
        }

        return true;
    }
    
    @Override
    public void scrollTo(int x, int y) {
        super.scrollTo(x, y);
        postInvalidate();
    }
}

在這個示例中,我們創建了一個 CustomScrollView 類,繼承自 ViewGroup,并實現了自定義的滾動邏輯。在 onInterceptTouchEvent 方法中我們攔截了觸摸事件,確保只有 CustomScrollView 處理觸摸事件。在 onTouchEvent 方法中,我們根據手指滑動的距離來進行垂直滾動。在 scrollTo 方法中,我們使用 postInvalidate() 方法來讓 View 重新繪制。

你可以根據自己的需求進一步擴展這個 CustomScrollView 類,例如添加更多的滾動效果、支持慣性滾動等功能。希望這個示例能幫助到你。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女