【问题标题】:Calculate width of Views so that they always fit on screen计算视图的宽度,使它们始终适合屏幕
【发布时间】:2016-11-14 16:04:37
【问题描述】:

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

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

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

现在所有的硬编码都是 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();
}

【问题讨论】:

  • 你现在如何为你的小部件充气?
  • @VladislavSazanovich 我通过调用 parent.addView(BarView) 绘制 CustomBarViews 并将宽度传递给 LayoutParams 但现在是硬编码。我需要根据要绘制的条数以某种方式计算条的宽度。
  • @VladislavSazanovich 我刚刚将我用于绘图的代码作为编辑添加到问题中,如果你可以看看的话。

标签: java android dynamic view width


【解决方案1】:

我觉得很有用

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

【讨论】:

  • 这在各自的情况下并没有真正的帮助!
【解决方案2】:

如果您有很多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

    }
}

【讨论】:

  • @drilonreqica。您需要onDraw() 中的更多代码吗?
猜你喜欢
  • 2012-05-19
  • 2012-06-05
  • 1970-01-01
  • 1970-01-01
  • 2013-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-04
相关资源
最近更新 更多