Ellipsize text in TextView without specifying maxL

2020-07-10 05:23发布

I have a TextView whose height would vary based on the other components in the screen. I have a long text to be set in this TextView and hence I would like to ellipsize it. Simply specifying android:ellipsize="end" is not working. Only on specifying maxLines along with it, the ellipsizing works. But I cannot specify a value for maxLines since the height of TextView is dynamic. How do I get the text ellipsized without specifying maxLines for the TextView?

1条回答
狗以群分
2楼-- · 2020-07-10 06:12

I found the solution to the problem by adding global layout listener. Following is the code snippet

tvDesc.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            tvDesc.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            int noOfLinesVisible = tvDesc.getHeight() / tvDesc.getLineHeight();

            tvDesc.setText(R.string.desc);

            tvDesc.setMaxLines(noOfLinesVisible);
            tvDesc.setEllipsize(TextUtils.TruncateAt.END);

        }
    });
查看更多
登录 后发表回答