【问题标题】:How to know what size a TextView WOULD be with certain string如何知道特定字符串的 TextView 的大小
【发布时间】:2015-03-15 04:16:07
【问题描述】:

也许我没有输入正确的关键字,但我没有找到答案。我想知道如果我用某个字符串设置 TextView 的尺寸是多少。但是,我想在活动中安排好所有内容之前了解一下。

我的 TextView 具有固定宽度和可变高度。我可以得到这样的高度:

myTextView.setText(myString);

// ... UI gets laid out ...

myTextView.getHeight()

如果高度超过某个点,我想更改 TextView 的宽度。 (但不是在那之前。)而不是等到 UI 布局之后,我想事先知道如果它有 myString 的高度是多少,然后在需要时更改宽度。

我查看了Layout 课程,但不知道该怎么做。我想知道它是否可能与覆盖 TextView 的 onMeasure 有关,但我真的不知道如何尝试。任何帮助表示赞赏。

更新

感谢@user3249477 和@0xDEADC0DE 的回答。我将@user3249477 的答案标记为现在的解决方案(尽管由于我需要多次调整视图大小,所以我不确定是否要反复打开和关闭可见性),但也给@0xDEADC0DE +1 以提供我需要的关键字进一步研究这个问题。

我需要对此进行更多的研究和测试。以下是迄今为止我发现有用的一些链接:

OnLayoutChangeListener:

measureText() 和 getTextBounds():

覆盖父视图的 onSizeChanged 看起来也很有趣:https://stackoverflow.com/a/14399163/3681880

【问题讨论】:

  • 我现在会使用StaticLayout 来解决这个问题。见this answer

标签: android textview


【解决方案1】:

您可以在不覆盖的情况下做到这一点。如果你得到TextViews PaintgetPaint(),你可以使用measureText(string) 来获得TextView 的最小值,当它用Paint 绘制时。我看起来像这样:

TextView textView = new TextView(this);
float textWidth = textView.getPaint().measureText("Some Text");

更新
要获取高度,您可以像这样在Paint 对象上调用getTextBounds()

    String text = "Some Text";
    Rect textBounds = new Rect();
    textView.getPaint().getTextBounds(text, 0, text.length(), textBounds);
    float height = textBounds.height();
    float width = textBounds.width();

【讨论】:

  • 这会返回文本宽度,而 OP 会询问 TextView 的高度。
  • 您的更新的问题是,它将所有文本都塞进了一行。所以 height 只是字体的高度。
【解决方案2】:

将您的TextView 设置为不可见:

android:visibility="invisible"

并测量它。完成后将其设置为可见:

TextView myTextView = (TextView) findViewById(R.id.text);
final int maxHeight = 500;
myTextView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom,
                               int oldLeft, int oldTop, int oldRight, int oldBottom) {
        v.removeOnLayoutChangeListener(this);

        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) v.getLayoutParams();
        Log.e("TAG", "H: " + v.getHeight() + " W: " + v.getWidth());

        if (v.getWidth() > maxHeight) {
            params.width += 100;
            v.setLayoutParams(params);
        }
        v.setVisibility(View.VISIBLE);
    }
});

【讨论】:

    猜你喜欢
    • 2012-02-01
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多