Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ellipsize text in TextView without specifying maxLines

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?

like image 898
DevAndroid Avatar asked Oct 09 '17 08:10

DevAndroid


1 Answers

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);

        }
    });
like image 124
DevAndroid Avatar answered Nov 09 '22 02:11

DevAndroid