ScrollView 與ListView 滑動沖突完美解決


一、介紹ListView高度的設置方法

二、根據實際需求解決沖突問題

 

一、介紹ListView高度的設置方法

在ScrollView中使用ListView,ListView的高度會不正常。

    方式一:在XML中寫死     

android:layout_width="match_parent"
android:layout_height="120dp"

    方式二:代碼中設置固定高度(如果在運行過程中才能決定ListView高度)

public void setHeight(int height){
  LayoutParams params = this.listview.getLayoutParams();  
  params.width = LayoutParams.FILL_PARENT;  
  params.height = height;  
  listview.setLayoutParams(layoutParams);
}

    方式三:代碼中動態設置高度(讓ListView高度最大 顯示完全所有數據)

public void setHeight(){  
    int height = 0;  
    int count = adapter.getCount();  
    for(int i=0;i<count;i++){  
        View temp = adapter.getView(i,null,listview);  
        temp.measure(0,0);  
        height += temp.getMeasuredHeight();  
    }  
    LayoutParams params = this.listview.getLayoutParams();  
    params.width = LayoutParams.FILL_PARENT;  
    params.height = height;  
    listview.setLayoutParams(layoutParams);  
}

 

二、根據實際需求解決沖突問題

前提1:ListView 顯示全部內容(假如4條數據 我顯示滿4條)

  上述方式三讓ListView高度最大,顯示完全數據,滑動時就只會響應ScrollView滑動事件

  此時ListView不能滑動,也沒必要滑動,因為已經顯示完全數據。

 

前提1:ListView 不想顯示全部內容(假如100條數據 我只顯示10條 滑動查看其余)

  使用上述方式一或二,ListView沒有顯示完全數據

  但是想焦點在ListView時滑動ListView,焦點在ScrollView時滑動ScrollView

  給ListView加上監聽OnTouchListener

listView.setOnTouchListener(new View.OnTouchListener() {
    
  @Override

  public boolean onTouch(View arg0, MotionEvent arg1) {
    scrollView.requestDisallowInterceptTouchEvent(true);

return false;
  }

}
);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM