2016-08-20 57 views
1

我創建了一個繪製圓的自定義視圖。它需要xml中的數字。根據父母調整視圖

例如其生成整個屏幕上10圈。

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

enter image description here

<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> 

但是,當我把這種觀點進入較小的佈局,圓根據視圖的寬度生成。我想根據父視圖生成。

我試圖覆蓋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中,對於自定義小部件,使layout_width =「match_parent」而不是在自定義視圖java類中實現,它將採用父寬度。

<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

謝謝,但我正在尋找一個java解決方案。我需要的是找到父母的大小 – user3792834

0

你可以通過父佈局的寬度,

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

有關自定義視圖強加父母的寬度(僅當自定義視圖layout_width沒有提到match_parent/WRAP_CONTENT)的解決方案,你需要重寫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); 
} 
相關問題