完美解決ListView, GridView在ScrollView顯示不徹底問題

在Android中,ListView, GridView是很好容器,用於規則展現條目,而且在超出範圍時能夠上下滑動展現更多。通常的,都是拿來單獨使用。 有時候,咱們須要把他們放在ScrollView中,不須要他們的滑動效果,僅僅用做展現效果,可是這個時候ListView,GridView每每展現不徹底。html

####解決辦法android

  • GridViewless

    public class GridViewInScrollView extends GridView {
    
          public GridViewInScrollView(Context context, AttributeSet attrs) {
              super(context, attrs);
          }
    
          public GridViewInScrollView(Context context) {
              super(context);
          }
    
          public GridViewInScrollView(Context context, AttributeSet attrs, int defStyle) {
              super(context, attrs, defStyle);
          }
    
          @Override
          public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
              int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                      MeasureSpec.AT_MOST);
              super.onMeasure(widthMeasureSpec, expandSpec);
          }
      }
  • ListViewide

    public class ListViewInScrollView extends ListView {
    
          public ListViewInScrollView(Context context, AttributeSet attrs) {
              super(context, attrs);
          }
    
          public ListViewInScrollView(Context context) {
              super(context);
          }
    
          public ListViewInScrollView(Context context, AttributeSet attrs, int defStyle) {
              super(context, attrs, defStyle);
          }
    
          @Override
          public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
              int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                      MeasureSpec.AT_MOST);
              super.onMeasure(widthMeasureSpec, expandSpec);
          }
      }

####分析ui

關鍵的代碼就是複寫了OnMeasure方法,在這個方法裏面利用MeasureSpec構建一個測量高度。先解釋下MeasureSpec這個類code

A MeasureSpec encapsulates the layout requirements passed from parent to child. Each MeasureSpec represents a requirement for either the width or the height. A MeasureSpec is comprised of a size and a mode. There are three possible modes:htm

UNSPECIFIED The parent has not imposed any constraint on the child. It can be whatever size it wants. EXACTLY The parent has determined an exact size for the child. The child is going to be given those bounds regardless of how big it wants to be. AT_MOST The child can be as large as it wants up to the specified size. MeasureSpecs are implemented as ints to reduce object allocation. This class is provided to pack and unpack the <size, mode> tuple into the int.three

MeasureSpec是一個幫助類,幫助記錄測量的屬性和數值。一個int的測量值能夠分紅兩個部分,後16位標識模式,前16位標識大小。三種模式在上面都有解釋。在ListView的源碼中能夠看到,在onMeasure方法中對AT_MOST模式作了特殊處理,調用了measureHeightOfChildren方法測量顯示高度。這個方法中計劃了每個view和高度和divider的高度以及ListView的padding,最終累加返回一個準確的高度。GridView也是同樣的道理。ci

相關文章
相關標籤/搜索