Scrollview 스크롤 위치 계산, 원하는 위치로 이동, child isvisible, scrollTo, smoothScrollTo

2020. 12. 16. 08:44모바일/Android_Java

Step1 CustomScrollView 생성

public class EventCustomScrollView extends ScrollView {
    private int mCurrentIndex;
    private OnScrollListener listener;

    public EventCustomScrollView(Context context){
        super(context);
        mCurrentIndex = 0 ;
    }

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

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        if(listener != null){
            listener.onScrollChanged(l,t,oldl,oldt);
        }
    }
    public void setOnScrollListener(OnScrollListener listener){
        this.listener = listener;
    }
    public interface OnScrollListener{
         void onScrollChanged(int l, int t, int oldl, int oldt);
    }
}

step2 ScrollView ScrollListener 등록

        scrollView.setOnScrollListener(new EventCustomScrollView.OnScrollListener() {
            int nowVisibleIndex = 0;
            @Override
            public void onScrollChanged(int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                Rect scrollBounds = new Rect();
                scrollView.getHitRect(scrollBounds);
                if (scrollY < oldScrollY) {
                    //스크롤 다운
                    //화면이 위로 올라감
                    for (int i = 0; i < imageViews.size(); i++) {
                        if (imageViews.get(i).getLocalVisibleRect(scrollBounds)) {
                            if (nowVisibleIndex > i) {
                                nowVisibleIndex = i;
                                setOutStanding(nowVisibleIndex);
                            }
                        }
                    }
                } else {
                    //스크롤 업
                    //화면이 아래로 내려감
                    for (int i = 0; i < imageViews.size(); i++) {
                        if (imageViews.get(i).getLocalVisibleRect(scrollBounds)) {
                            if (nowVisibleIndex < i) {
                                nowVisibleIndex = i;
                                setOutStanding(nowVisibleIndex);
                            }
                        }
                    }
                }
            }
        });

step3 화면에 보여지는 ScrollView 영역 표시

    private void setOutStanding(int index) {
        for (int i = 0; i < 5; i++) {
            if (i == index) {
                buttons[i].setBackgroundColor(getResources().getColor(R.color.color04));
            } else {
                buttons[i].setBackgroundColor(getResources().getColor(R.color.color01));
            }
        }
    }