计算视图的宽度,使它们始终适合屏幕

时间:2016-07-12 12:05:44

标签: java android dynamic view width

我需要动态计算我绘制的图表中条形的宽度。

最小宽度必须为4像素,最大为50像素。

如何计算宽度,以便即使我需要更多条形,它们也会动态设置宽度并适合屏幕?

现在,所有HardCoded都是4或50像素,所以如果你能提出建议我会感激不尽。

提前致谢!

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

2 个答案:

答案 0 :(得分: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

    }
}

答案 1 :(得分:0)

我认为这将是有用的

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