programing tip

Android ListView에서 프로그래밍 방식으로 특정 위치로 스크롤

itbloger 2020. 6. 10. 22:39
반응형

Android ListView에서 프로그래밍 방식으로 특정 위치로 스크롤


어떻게 프로그래밍 방식으로 특정 위치로 스크롤 할 수 ListView있습니까?

예를 들어,가 있고 String[] {A,B,C,D....}의 맨 위에 보이는 항목 ListView을 my의 인덱스 21 로 설정해야합니다 String[].


직접 스크롤의 경우 :

getListView().setSelection(21);

부드러운 스크롤 :

getListView().smoothScrollToPosition(21);

스크롤 시간이있는 SmoothScroll의 경우 :

getListView().smoothScrollToPositionFromTop(position,offset,duration);

매개 변수
position->
오프셋 으로 스크롤 할 위치 ----> 스크롤이 완료 될 때 뷰의 상단에서 원하는 위치의 픽셀 단위 거리-> 스크롤
에 사용할 밀리 초 수

참고 : API 11부터

HandlerExploit의 대답은 내가 찾던 것이었지만 내 목록보기는 상당히 길며 알파벳 스크롤러도 있습니다. 그런 다음 동일한 함수가 다른 매개 변수를 취할 수 있음을 발견했습니다. :)


편집 : (AFD 제안에서)

현재 선택을 배치하려면

int h1 = mListView.getHeight();
int h2 = listViewRow.getHeight();

mListView.smoothScrollToPositionFromTop(position, h1/2 - h2/2, duration);  

다음과 같이 코드를 핸들러에 넣습니다.

public void timerDelayRunForScroll(long time) {
        Handler handler = new Handler(); 
        handler.postDelayed(new Runnable() {           
            public void run() {   
                try {
                    lstView.smoothScrollToPosition(YOUR_POSITION);
                } catch (Exception e) {}
            }
        }, time); 
    }

그런 다음이 방법을 호출하십시오.

timerDelayRunForScroll(100);

건배!!!


Listview표시되지 다음이를 사용하는 경우 스크롤이 스크롤에 기본적으로 상단에 위치하지만, 원하는 될 것입니다 :

if (listView1.getFirstVisiblePosition() > position || listView1.getLastVisiblePosition() < position)
            listView1.setSelection(position);

OnGroupExpandListener를 설정하고 onGroupExpand ()를 다음과 같이 재정의했습니다.

setSelectionFromTop () 메서드를 사용하여 선택한 항목을 설정하고 ListView의 위쪽 가장자리에서 선택 항목을 y 픽셀로 배치합니다. (터치 모드 인 경우 항목이 선택되지 않지만 여전히 적절하게 배치됩니다.) (android docs)

    yourlist.setOnGroupExpandListener (new ExpandableListView.OnGroupExpandListener()
    {

        @Override
        public void onGroupExpand(int groupPosition) {

            expList.setSelectionFromTop(groupPosition, 0);
            //your other code
        }
    });

UP / DOWN 버튼을 사용하여 스크롤 목록보기

If someone is interested in handling listView one row up/down using button. then.

public View.OnClickListener onChk = new View.OnClickListener() {
             public void onClick(View v) {

                 int index = list.getFirstVisiblePosition();
                 getListView().smoothScrollToPosition(index+1); // For increment. 

}
});

If someone looking for a similar functionality like Gmail app,

The Listview scroll will be positioned to top by default. Thanks for the hint. amalBit. Just subtract it. That's it.

 Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            int h1 = mDrawerList.getHeight();
            int h2 = header.getHeight();
            mDrawerList.smoothScrollToPosition(h2-h1);
        }
    }, 1000);

If you want to jump directly to the desired position in a listView just use

listView.setSelection(int position);

and if you want to jump smoothly to the desired position in listView just use

listView.smoothScrollToPosition(int position);


This is what worked for me. Combination of answers by amalBit & Melbourne Lopes

public void timerDelayRunForScroll(long time) {
    Handler handler = new Handler(); 
    handler.postDelayed(new Runnable() {           
        public void run() {   
            try {
                  int h1 = mListView.getHeight();
                  int h2 = v.getHeight();

                  mListView.smoothScrollToPositionFromTop(YOUR_POSITION, h1/2 - h2/2, 500);  

            } catch (Exception e) {}
        }
    }, time); 
}

and then call this method like:

timerDelayRunForScroll(400);

its easy list-view.set selection(you pos); or you can save your position with sharedprefrenceand when you start activity it get preferences and setseletion to that int


-If you just want the list to scroll up\dawn to a specific position:

myListView.smoothScrollToPosition(i);

-if you want to get the position of a specific item in myListView:

myListView.getItemAtPosition(i);

-also this myListView.getVerticalScrollbarPosition(i);can helps you.

Good Luck :)


I found this solution to allow the scroll up and down using two different buttons.

As suggested by @Nepster I implement the scroll programmatically using the getFirstVisiblePosition() and getLastVisiblePosition() to get the current position.

final ListView lwresult = (ListView) findViewById(R.id.rds_rdi_mat_list);
    .....

        if (list.size() > 0) {
            ImageButton bnt = (ImageButton) findViewById(R.id.down_action);
            bnt.setVisibility(View.VISIBLE);
            bnt.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if(lwresult.getLastVisiblePosition()<lwresult.getAdapter().getCount()){
                        lwresult.smoothScrollToPosition(lwresult.getLastVisiblePosition()+5);
                    }else{
                        lwresult.smoothScrollToPosition(lwresult.getAdapter().getCount());

                    }
                }
            });
            bnt = (ImageButton) findViewById(R.id.up_action);
            bnt.setVisibility(View.VISIBLE);

            bnt.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if(lwresult.getFirstVisiblePosition()>0){
                        lwresult.smoothScrollToPosition(lwresult.getFirstVisiblePosition()-5);
                    }else{
                        lwresult.smoothScrollToPosition(0);
                    }

                }
            });
        }

참고URL : https://stackoverflow.com/questions/7561353/programmatically-scroll-to-a-specific-position-in-an-android-listview

반응형