android實現兩個listview的同步滾動

在開發的過程當中看到項目有實現兩個listview同步滾動的效果,因此就但願跟你們分享一下!! java

不用說你們可能也想到在listview的onScrollListener中作一些操做, ide

 

如今具體的細節以下: code

public void setListViewOnTouchAndScrollListener(final ListView listView1,final ListView listView2){ 
          
            
         //設置listview2列表的scroll監聽,用於滑動過程當中左右不一樣步時校訂 
         listView2.setOnScrollListener(new OnScrollListener() { 
     
    @Override 
    public void onScrollStateChanged(AbsListView view, int scrollState) { 
     //若是中止滑動 
     if(scrollState == 0 || scrollState == 1){ 
      //得到第一個子view 
      View subView = view.getChildAt(0); 
       
      if(subView !=null){ 
       final int top = subView.getTop(); 
       final int top1 = listView1.getChildAt(0).getTop(); 
       final int position = view.getFirstVisiblePosition(); 
        
       //若是兩個首個顯示的子view高度不等 
       if(top != top1){ 
        listView1.setSelectionFromTop(position, top); 
       } 
      } 
     } 
      
    } 
     
    public void onScroll(AbsListView view, final int firstVisibleItem, 
      int visibleItemCount, int totalItemCount) { 
     View subView = view.getChildAt(0); 
     if(subView != null){ 
      final int top = subView.getTop(); 
  
//      //若是兩個首個顯示的子view高度不等 
      int top1 = listView1.getChildAt(0).getTop(); 
      if(!(top1 - 7 < top &&top < top1 + 7)){ 
       listView1.setSelectionFromTop(firstVisibleItem, top); 
       listView2.setSelectionFromTop(firstVisibleItem, top); 
      } 
      
     } 
    } 
   }); 
         
       //設置listview1列表的scroll監聽,用於滑動過程當中左右不一樣步時校訂 
         listView1.setOnScrollListener(new OnScrollListener() { 
     
    @Override 
    public void onScrollStateChanged(AbsListView view, int scrollState) { 
    if(scrollState == 0 || scrollState == 1){ 
      //得到第一個子view 
      View subView = view.getChildAt(0); 
       
      if(subView !=null){ 
       final int top = subView.getTop(); 
       final int top1 = listView2.getChildAt(0).getTop(); 
       final int position = view.getFirstVisiblePosition(); 
        
       //若是兩個首個顯示的子view高度不等 
       if(top != top1){ 
        listView1.setSelectionFromTop(position, top); 
        listView2.setSelectionFromTop(position, top); 
       } 
      } 
     } 
    } 
     
    @Override 
    public void onScroll(AbsListView view, final int firstVisibleItem, 
      int visibleItemCount, int totalItemCount) { 
     View subView = view.getChildAt(0); 
     if(subView != null){ 
      final int top = subView.getTop(); 
      listView1.setSelectionFromTop(firstVisibleItem, top); 
     listView2.setSelectionFromTop(firstVisibleItem, top); 
      
     } 
    } 
   }); 
 }
相關文章
相關標籤/搜索