IT

Android에서 ScrollView를 프로그래밍 방식으로 스크롤 할 수 있습니까?

lottoking 2020. 6. 23. 07:04
반응형

Android에서 ScrollView를 프로그래밍 방식으로 스크롤 할 수 있습니까?


ScrollView프로그래밍 방식으로 특정 위치 로 스크롤하는 방법이 있습니까?

TableLayout배치 된 동적 만들었습니다 ScrollView. 따라서 특정 작업 (예 : 버튼 클릭 등)에서 특정 행이 자동으로 맨 위 위치로 스크롤되도록하고 싶습니다.

가능합니까?


ScrollView sv = (ScrollView)findViewById(R.id.scrl);
sv.scrollTo(0, sv.getBottom());

또는

sv.scrollTo(5, 10);


Pragna의 답변이 항상 작동하지는 않습니다.

mScrollView.post(new Runnable() { 
        public void run() { 
             mScrollView.scrollTo(0, mScrollView.getBottom());
        } 
});

또는

mScrollView.post(new Runnable() { 
        public void run() { 
             mScrollView.fullScroll(mScrollView.FOCUS_DOWN);
        } 
});

스크롤하여 시작하려는 경우

mScrollView.post(new Runnable() { 
        public void run() { 
             mScrollView.fullScroll(mScrollView.FOCUS_UP);
        } 
});

onViewView () 직후에 scrollView를 스크롤하기를 원했습니다 (예 : 버튼 클릭 후). 제대로 작동하려면 ViewTreeObserver를 사용해야했습니다.

mScrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            mScrollView.post(new Runnable() {
                public void run() {
                    mScrollView.fullScroll(View.FOCUS_DOWN);
                }
            });
        }
    });

그러나 무언가가 레이아웃 될 때마다 (예를 들어 보이지 않는 또는 유사한 뷰를 설정하는 경우) 호출 될 것이므로 더 이상 필요하지 않은 경우이 리스너를 제거하는 것을 잊지 마십시오.

public void removeGlobalOnLayoutListener (ViewTreeObserver.OnGlobalLayoutListener victim) SDK Lvl <16에서

또는

public void removeOnGlobalLayoutListener (ViewTreeObserver.OnGlobalLayoutListener victim) SDK Lvl에서> 16


다음과 같이 사용하십시오 :

mScrollView.scrollBy(10, 10);

또는

mScrollView.scrollTo(10, 10);

여기에 좋은 답변이 많이 있지만 한 가지만 추가하고 싶습니다. 때로는 상단 또는 하단으로 전체 스크롤하는 대신 ScrollView를 특정 레이아웃보기로 스크롤하려고 할 때가 있습니다.

간단한 예 : 등록 양식에서 양식의 편집 텍스트가 채워지지 않은 상태에서 사용자가 "서명"버튼을 누르면 해당 편집 텍스트로 스크롤하여 해당 필드를 채워야한다고 사용자에게 알려야합니다.

이 경우 다음과 같은 작업을 수행 할 수 있습니다.

scrollView.post(new Runnable() { 
        public void run() { 
             scrollView.scrollTo(0, editText.getBottom());
        } 
});

또는 인스턴트 스크롤 대신 부드러운 스크롤을 원할 경우 :

scrollView.post(new Runnable() { 
            public void run() { 
                 scrollView.smoothScrollTo(0, editText.getBottom());
            } 
    });

텍스트 편집 대신 모든 유형의보기를 사용할 수 있습니다. getBottom ()은 부모 레이아웃을 기준으로보기의 좌표를 반환하므로 ScrollView 내부에 사용 된 모든보기에는 부모 만 있어야합니다 (예 : 선형 레이아웃).

ScrollView의 자식 안에 여러 부모가있는 경우 찾은 유일한 해결책은 부모보기에서 requestChildFocus를 호출하는 것입니다.

editText.getParent().requestChildFocus(editText, editText);

그러나이 경우에는 부드러운 스크롤을 가질 수 없습니다.

이 답변이 동일한 문제를 가진 사람을 도울 수 있기를 바랍니다.


scrollTo방법을 사용 해보세요 추가 정보


즉시 스크롤하려면 다음을 사용할 수 있습니다.

ScrollView scroll= (ScrollView)findViewById(R.id.scroll);
scroll.scrollTo(0, scroll.getBottom());

            OR

scroll.fullScroll(View.FOCUS_DOWN);

            OR

scroll.post(new Runnable() {            
    @Override
    public void run() {
           scroll.fullScroll(View.FOCUS_DOWN);              
    }
});

또는 부드럽고 천천히 스크롤하려면 다음을 사용할 수 있습니다.

private void sendScroll(){
        final Handler handler = new Handler();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {Thread.sleep(100);} catch (InterruptedException e) {}
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        scrollView.fullScroll(View.FOCUS_DOWN);
                    }
                });
            }
        }).start();
    }

TextView가있는 ScrollView의 맨 아래로 스크롤하도록이 작업을 수행했습니다.

(TextView를 업데이트하는 메소드에 넣었습니다)

final ScrollView myScrollView = (ScrollView) findViewById(R.id.myScroller);
    myScrollView.post(new Runnable() {
    public void run() {
        myScrollView.fullScroll(View.FOCUS_DOWN);
    }
});

그래 넌 할수있어.

하나가 Layout있고 그 안에 많은 것이 있다고 가정 해 봅시다 Views. 따라서 View프로그래밍 방식 으로 스크롤하려면 다음 코드 스 니펫을 작성해야합니다.

예 :

content_main.xml

<ScrollView
    android:id="@+id/scrollView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <Button
            android:id="@+id/btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/txtView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>
</ScrollView>

MainActivity.java

ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView);
Button btn = (Button) findViewById(R.id.ivEventBanner);
TextView txtView = (TextView) findViewById(R.id.ivEditBannerImage);

특정 경우로 스크롤하려면 이 경우 txtviewView 라고 말 하십시오 .

scrollView.smoothScrollTo(txtView.getScrollX(),txtView.getScrollY());

그리고 당신은 끝났습니다. .


참고 : 이미 스레드에있는 경우 새 포스트 스레드를 만들어야하거나 전체 끝까지 나에게 긴 높이를 스크롤하지 않습니다. 예를 들어 :

void LogMe(final String s){
    runOnUiThread(new Runnable() {
        public void run() {
            connectionLog.setText(connectionLog.getText() + "\n" + s);
            final ScrollView sv = (ScrollView)connectLayout.findViewById(R.id.scrollView);
            sv.post(new Runnable() {
                public void run() {
                    sv.fullScroll(sv.FOCUS_DOWN);
                    /*
                    sv.scrollTo(0,sv.getBottom());
                    sv.scrollBy(0,sv.getHeight());*/
                }
            });
        }
    });
}

좌표가 포함되지 않은 다른 답변 추가.

이렇게하면 원하는 뷰가 초점을 맞출 수 있지만 상단 위치는 아닙니다.

  yourView.getParent().requestChildFocus(yourView,yourView);

public void RequestChildFocus (자식보기, 초점보기)

아이 - 초점을 원하는이 ViewParent의 아이입니다. 이 뷰에는 포커스 된 뷰가 포함됩니다. 실제로 포커스가있는 것은 아닙니다.

집중 -실제로 초점이있는 자녀의 후손


** 원하는 높이까지 스크롤합니다. 나는 좋은 해결책을 생각해 냈습니다. **

                scrollView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        scrollView.scrollBy(0, childView.getHeight());
                    }
                }, 100);

just page scroll:

ScrollView sv = (ScrollView) findViewById(your_scroll_view);
sv.pageScroll(View.FOCUS_DOWN);

Everyone is posting such complicated answers.

I found an easy answer, for scrolling to the bottom, nicely:

final ScrollView myScroller = (ScrollView) findViewById(R.id.myScrollerView);

// Scroll views can only have 1 child, so get the first child's bottom,
// which should be the full size of the whole content inside the ScrollView
myScroller.smoothScrollTo( 0, myScroller.getChildAt( 0 ).getBottom() );

And, if necessary, you can put the second line of code, above, into a runnable:

myScroller.post( new Runnable() {
    @Override
    public void run() {
        myScroller.smoothScrollTo( 0, myScroller.getChildAt( 0 ).getBottom() );
    }
}

It took me much research and playing around to find this simple solution. I hope it helps you, too! :)


I was using the Runnable with sv.fullScroll(View.FOCUS_DOWN); It works perfectly for the immediate problem, but that method makes ScrollView take the Focus from the entire screen, if you make that AutoScroll to happen every time, no EditText will be able to receive information from the user, my solution was use a different code under the runnable:

sv.scrollTo(0, sv.getBottom() + sv.getScrollY());

making the same without losing focus on important views

greetings.


it's working for me

mScrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            mScrollView.post(new Runnable() {
                public void run() {
                    mScrollView.fullScroll(View.FOCUS_DOWN);
                }
            });
        }
    });

private int totalHeight = 0;

ViewTreeObserver ScrollTr = loutMain.getViewTreeObserver();
ScrollTr.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
            loutMain.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        } else {
            loutMain.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
        TotalHeight = loutMain.getMeasuredHeight();

    }
});

scrollMain.smoothScrollTo(0, totalHeight);

I had to create Interface

public interface ScrollViewListener {
    void onScrollChanged(ScrollViewExt scrollView, 
                         int x, int y, int oldx, int oldy);
}    

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ScrollView;

public class CustomScrollView extends ScrollView {
    private ScrollViewListener scrollViewListener = null;
    public ScrollViewExt(Context context) {
        super(context);
    }

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

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

    public void setScrollViewListener(ScrollViewListener scrollViewListener) {
        this.scrollViewListener = scrollViewListener;
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        if (scrollViewListener != null) {
            scrollViewListener.onScrollChanged(this, l, t, oldl, oldt);
        }
    }
}




<"Your Package name ".CustomScrollView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/scrollView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusableInTouchMode="true"
    android:scrollbars="vertical">

    private CustomScrollView scrollView;

scrollView = (CustomScrollView)mView.findViewById(R.id.scrollView);
        scrollView.setScrollViewListener(this);


    @Override
    public void onScrollChanged(ScrollViewExt scrollView, int x, int y, int oldx, int oldy) {
        // We take the last son in the scrollview
        View view = (View) scrollView.getChildAt(scrollView.getChildCount() - 1);
        int diff = (view.getBottom() - (scrollView.getHeight() + scrollView.getScrollY()));

        // if diff is zero, then the bottom has been reached
        if (diff == 0) {
                // do stuff
            //TODO keshav gers
            pausePlayer();
            videoFullScreenPlayer.setVisibility(View.GONE);

        }
    }

참고URL : https://stackoverflow.com/questions/6438061/can-i-scroll-a-scrollview-programmatically-in-android

반응형