Home Ask Login Register

Developers Planet

Your answer is one click away!

Cabezas February 2016

How to know if there is available space in TextView?

Because I would like to make the same, like Whatsapp, it puts message and hour in the same line

enter image description here

or in another line.

Sometimes there is space and Whatsapp puts the hour in same line. However sometimes there is not space and Whatsapp puts the hour in other line.

Inside or outside...

Any idea?

Answers


Daniel Zolnai February 2016

I think you can give textView.getLayout().getLineWidth(lineNum) a try (lineNum is obviously the last line). Then compare it to the parent layout width, and if the difference is bigger than timestamp.getWidth() plus some extra padding, then you display it on the same line.


Cabezas February 2016

public static final String TAG = "MainActivity";
private TextView mText;
private RelativeLayout relativeLayout;
private Boolean mFirstTime = true;
private static final int WIDH_HOUR = 382;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    final int width = getScreensWidh();

    mText = (TextView) findViewById(R.id.activity_main_text);
    relativeLayout = (RelativeLayout) findViewById(R.id.activity_main_relative);

    mText.setText("aaaaa dfsafsa afdsfa fdsafas adfas fdasf adfsa dsa aaaa dfsafsa afdsfa fdsafas adfas fdasf adfsa");

    ViewTreeObserver vto = mText.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (mFirstTime) {
                Layout layout = mText.getLayout();
                int lines = layout.getLineCount();

                int offset = layout.layout.getLineWidth(lines - 1);
                int freeSpace = width - offset;

                TextView hour = new TextView(MainActivity.this);
                hour.setText("12:20");
                RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
                params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                if (freeSpace > WIDH_HOUR) {
                    params.addRule(RelativeLayout.ALIGN_BOTTOM, R.id.activity_main_text);
                } else {
                    params.addRule(RelativeLayout.BELOW, R.id.activity_main_text);
                }
                hour.setLayoutParams(params);
                relativeLayout.addView(hour);
                Log.d(TAG, String.valueOf(freeSpace));
                mFirstTime = false;
            }

        }
    });


}

public int getScreensWidh() {
    Display display = getWindowManager().get 

Post Status

Asked in February 2016
Viewed 1,457 times
Voted 11
Answered 2 times

Search




Leave an answer


Quote of the day: live life