2016-08-20 3 views
1

서클을 그리는 사용자 정의보기를 만들었습니다. 그것은 XML에서 원의 숫자가 걸립니다.크기 조정보기 부모에 따라

예를 들어 전체 화면에서 10 원을 생성합니다.

<com.dd.view.MyShape 
    android:layout_width="match_parent" 
    android:layout_height="60dp" 
    app:shape_count="10"/> 

<LinearLayout 
    android:layout_width="80dp" 
    android:layout_height="wrap_content" 
    android:orientation="vertical"> 

    <com.dd.view.MyShape 
     android:layout_width="100dp" 
     android:layout_height="60dp" 
     app:shape_count="3"/> 
</LinearLayout> 

enter image description here 하지만 작은 레이아웃에이보기를 둘 때, 원은 뷰의 폭에 따라 생성합니다. 부모보기에 따라 생성하고 싶습니다.

onMeasure 메서드를 재정의하려했지만 올바르게 적용 할 수 없었습니다. 지금 보이는 같은 :

enter image description here

그리고 여기 내 된 onDraw 방법 : 귀하의 답변

@Override 
protected void onDraw(Canvas canvas) { 
    super.onDraw(canvas); 
    int totalWidth=getMeasuredWidth(); 
    int major = totalWidth/circleCount; 
    int radius = major/2; 
    float startPoint = totalWidth/(circleCount * 2); 
    for (int i = 0; i < circleCount; i++) { 
     if (i % 2 == 0) paint.setColor(Color.GREEN); 
     else paint.setColor(Color.BLUE); 
     canvas.drawCircle(startPoint + major * i, radius,radius, paint); 
    } 
} 

감사합니다.

답변

1

xml에서 사용자 정의 위젯의 경우 사용자 정의보기 Java 클래스에서 달성하는 것이 아니라 layout_width = "match_parent"를 작성하면 부모의 너비가됩니다.

<LinearLayout 
    android:layout_width="80dp" 
    android:layout_height="wrap_content" 
    android:orientation="vertical"> 

    <com.dd.view.MyShape 
     android:layout_width="match_parent" 
     android:layout_height="60dp" 
     app:shape_count="3"/> 

</LinearLayout> 
+0

고마워요.하지만 자바 솔루션을 찾고 있습니다. 부모 크기를 찾는 것뿐이에요. – user3792834

0
당신은 부모 및 레이아웃의 폭을 얻을 수

, 사용자 지정보기에 (사용자 정의보기 layout_width가 match_parent/wrap_content 언급되지 않은 경우에만) 부모의 폭을 부과의 솔루션을

View parent = (View)(this.getParent()); 
width = parent.getLayoutParams().width 

, 당신은 오버라이드 (override) 할 필요가 onMeasure().

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

    int width = 0; 

    if(getLayoutParams().width == ViewGroup.LayoutParams.MATCH_PARENT){ 

     width = MeasureSpec.getSize(widthMeasureSpec); 

    }else if(getLayoutParams().width == ViewGroup.LayoutParams.WRAP_CONTENT){ 

     width = MeasureSpec.getSize(widthMeasureSpec); 

    }else{ 
     View parent = (View)(this.getParent()); 

     width = parent.getLayoutParams().width; 
    } 

    setMeasuredDimension(width,heightMeasureSpec); 
} 
관련 문제