2017-07-04 22 views
1

我的自定義視圖的代碼:定製視圖延伸的LinearLayout不能Android中n,而是在Android的m個顯示非常

public class IndicatorView extends LinearLayout { 
private int[] mColors = new int[]{Color.RED, Color.GREEN, Color.MAGENTA, Color.BLUE, Color.YELLOW, Color.GRAY}; 

public IndicatorView(Context context, @Nullable AttributeSet attrs) { 
    super(context, attrs); 
    init(); 
} 

private void init() { 
    this.setOrientation(LinearLayout.HORIZONTAL); 
    fillParent(); 
} 

private void fillParent() { 
    for(int i = 0;i<6;i++) { 
     TextView textView = new TextView(getContext()); 
     textView.setText("i"); 
     textView.setBackgroundColor(mColors[i]); 
     textView.setLayoutParams(new LayoutParams(0, LayoutParams.WRAP_CONTENT, 1.0F)); 
     this.addView(textView); 
    } 
} 

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
    super.onMeasure(widthMeasureSpec, heightMeasureSpec); 

    int desiredWidth = this.getChildAt(0).getWidth() + getPaddingLeft() + getPaddingRight(); 

    int widthMode = MeasureSpec.getMode(widthMeasureSpec); 
    int indicatorViewWidth = MeasureSpec.getSize(widthMeasureSpec); 
    int heightMode = MeasureSpec.getMode(heightMeasureSpec); 
    int indicatorViewHeight = MeasureSpec.getSize(heightMeasureSpec); 
    switch (widthMode) { 
     case MeasureSpec.EXACTLY: 
      break; 
     case MeasureSpec.AT_MOST: 
      indicatorViewWidth = Math.min(desiredWidth, indicatorViewWidth); 
      break; 
     case MeasureSpec.UNSPECIFIED: 
      indicatorViewWidth = desiredWidth; 
      break; 
    } 

    setMeasuredDimension(indicatorViewWidth,indicatorViewHeight); 
} 

}

這是結果在版本的Android M: enter image description here 。這是Android N中的結果: enter image description here 。在日誌中,desiredWidth始終爲0。 我知道Android N之後View的度量方法有一些變化,但是我的代碼&如何解決它呢?

回答

0

更改爲

int desiredWidth = this.getChildAt(0).getMeasureWidth() + getPaddingLeft() + getPaddingRight(); 

的問題可以得到解決。

相關問題