Measure TextView height - auto wrap

时间:2016-11-02 16:32:28

标签: android android-layout height android-view measure

I've created an expandable cardview, which contains a title, subtitle and a detail textview.

Now I want to get the height dynamically depending on the height of the text in a textview with wrap_content. So I used the .measure method on my view in the onClickListener:

holder.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
           holder.getDetailText().measure(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
           Log.i("Project", ""+ holder.getDetailText().getMeasuredHeight());
    }

});

I get a height of 57 with this text:

holder.getDetailText().setText("Test Test Test Test");

If I now add a longer text in there which automatically wraps to multiple lines I get the same height of 57

holder.getDetailText().setText("Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test ...");

As soon as I put a text with new line feed in there everything works as expected which results in a height of 155

holder.getDetailText().setText("Test\nTest\nTest");

So how is it possible to get the actually height of the textview with automatically wrapped text?

Update: This is a very long text which is automatically wrapped, but I get the height of 57, so it will only display the first line, because the getMeasuredHeight only returns this (57) height. enter image description here

向下滚动页面

我期望但不起作用,因为getMeasuredHeight返回错误的高度: enter image description here

如果我手动添加\n Feed,那么没有自动换行getMeasuredHeight返回正确的高度,一切都按预期工作。 enter image description here

似乎.measure忽略了宽度,因为即使我放置一个常量值,getMeasuredHeight返回的高度也不会改变。

1 个答案:

答案 0 :(得分:0)

对于长文本TextView需要花时间进行渲染,在此之前我们正在计算TextView的高度。

使用下面的代码      view.setText(“测试测试测试测试测试测试测试测试测试测试测试测试测试测试...”);

                view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        Toast.makeText(getApplicationContext(), "Height :- " + view.getMeasuredHeight(), Toast.LENGTH_SHORT).show();

                    }
                });

请参阅How to find the Text Area(Height/Width) of TextView programmatically in android

如果您想查看TextView的确切行为,请创建customTextView并查看其生命周期的行为

请告诉我它是否适合你。