2017-07-04 2 views
1

mon code de vue personnalisée:vue personnalisée étend LinearLayout ne peut pas afficher dans Android N mais dans Android M est bien

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); 
} 

}

Ceci est le résultat dans Android M: enter image description here .Cette est le résultat dans Android N: enter image description here .La Largeur désirée est toujours 0 voir dans Log. Je sais qu'il y a quelques changements dans la méthode de mesure de View après Android N, mais quel est le problème dans mon code & comment le résoudre?

Répondre

0

Modification

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

le problème peut être résolu.