Ragini
Ragini

Reputation: 332

Split text into new line if text exceeds the device width

How to split the text to new line if text is larger than the device width?

For eg.

aaaaa bbbbbbbb
bbbb

Expected Output-
aaaaa
bbbbbbbbbbbbbb

Upvotes: 1

Views: 619

Answers (2)

Ragini
Ragini

Reputation: 332

Below solution is working -

txtUserName.post(new Runnable()
            {  
                @Override  
                public void run()
                {

                    int textviewWidth = getTextviewWidth(text, getWidthOfScreen());

                    int deviceWidth = getWidthOfScreen();

                    if (textviewWidth >= deviceWidth)
                    {

                        String userName = text.replace(" ", "\n");

                        txtUserName.setText(userName);
                    }
                }
            });


public int getTextviewWidth(String text, int deviceWidth)
    {

        txtUserName.setText(text);
        int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(deviceWidth, View.MeasureSpec.AT_MOST);
        int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        txtUserName.measure(widthMeasureSpec, heightMeasureSpec);
        return txtUserName.getMeasuredWidth();
    }

 public int getWidthOfScreen()
    {

        DisplayMetrics displaymetrics = new DisplayMetrics();
        (mContext).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int height = displaymetrics.heightPixels;
        int width = displaymetrics.widthPixels;

        return width;

    }

Upvotes: 0

vishal patel
vishal patel

Reputation: 294

Just use "\n" where ever you want to split the text.

Upvotes: 2

Related Questions