2016-07-12 1 views
0

私が描いている図のバーの幅を動的に計算する必要があります。常に画面に収まるようにビューの幅を計算する

最小幅は4ピクセル、最大値は50ピクセルです。

どのようにして幅を計算すると、バーがさらに必要な場合でも、動的に幅を設定して画面に収まるようにしますか?

今はすべてが4または50ピクセルになるようにハードコードされています。何かを提案できれば感謝しています。

ありがとうございます!

EDIT 1

public void drawBars(int numberOfRates) { 
    this.removeAllViews(); 
    final ViewGroup nullParent = null; 
    this.addView(mInflater.inflate(R.layout.layout_bar_diagram, nullParent)); 
    LinearLayout parentView = (LinearLayout) findViewById(R.id.parentView); 

    int width, height, horizontalMargin, verticalMargin, textBottomMargin; 

    verticalMargin = calculateDpi(16); 

    if (((numberOfRates * calculateDpi(50)) + (numberOfRates * calculateDpi(5))) < displayMetrics.widthPixels) { 
     width = calculateDpi(50); 
     horizontalMargin = calculateDpi(5); 
    } else { 
     width = 0; 
     horizontalMargin = 0; 
    } 

    for (int i = 0; i < numberOfRates; i++) { 

     if (i == 0) { 
      textBottomMargin = 0; 
      height = calculateDpi(50); 
     } else if (i == (numberOfRates - 1)) { 
      textBottomMargin = calculateDpi(16); 
      height = calculateDpi(150); 
     } else { 
      textBottomMargin = calculateDpi(16); 
      height = calculateDpi(100); 
     } 

     TextBarView textBarView = new TextBarView(getContext()); 

     textBarView.drawBar(i + 1, 
       width, 
       height, 
       horizontalMargin, 
       verticalMargin, 
       textBottomMargin); 

     parentView.addView(textBarView); 
    } 

    invalidate(); 
} 

Example 1

Example 2

私はそれが便利になると思うExample 3

+0

あなたのウィジェットはどのように膨張していますか? –

+0

@ VladislavSazanovich私はparent.addView(BarView)を呼び出してCustomBarViewsを描画し、LayoutParamsに幅を渡しますが、これは現在HardCodedです。どのくらいバーを描画したいのかに応じてバーの幅を計算する必要があります。 – drilonreqica

+0

@ VladislavSazanovich私はあなたが一見することができる場合、私は質問にEDITとして描画のために使用するコードを追加しました。 – drilonreqica

答えて

0

ViewGroup.LayoutParams layoutParams = btn.getLayoutParams(); 
    int width =layoutParams.width; 
    int hight=layoutParams.height; 
+0

これはそれぞれの場合に本当に役立つものではありません! – drilonreqica

1

Viewsが多い場合は、ViewGroupに追加することはお勧めできません。私はあなたのウィジェットをCanvasに描くことをお勧めします。

public class CustomDiagram extends View { 

    private int numberOfItems; 

    public CustomDiagram(Context context) { 
     super(context); 
    } 

    public CustomDiagram(Context context, AttributeSet attrs) { 
     super(context, attrs); 
    } 

    public CustomDiagram(Context context, AttributeSet attrs, int defStyleAttr) { 
     super(context, attrs, defStyleAttr); 
    } 

    @Override 
    protected void onDraw(Canvas canvas) { 
     super.onDraw(canvas); 

     int width = getMeasuredWidth(); 
     // Here you have full width of your view 
     // You also have numberOfItems here 

    } 
} 
+0

@ drillonreqica。 'onDraw()'にもっとコードが必要ですか? –

関連する問題