How can I tell if my actionbar's title is going to be truncated?

Viewed 514

In my app I want to display two pieces of information in the title of the actionbar. However since the title can be of various length, some devices will not be able to display both pieces of information. If this happens then I can display the second string using getSupportActionBar().setSubtitle.

However, the issue I'm having is that I don't know how to check if the title is going to be truncated. I've tried using getSupportActionBar().isTitleTruncated(), however this always returns false.

        if (getSupportActionBar().isTitleTruncated())
        {
            getSupportActionBar().setTitle(username);
            getSupportActionBar().setSubtitle("❤" + " " + String.valueOf(rating));
        }
        else
        {
            getSupportActionBar().setTitle(username + "  " + "❤" + " " + String.valueOf(rating));
        }

According to this https://code.google.com/p/android/issues/detail?id=81987 isTitleTruncated() requires a layout pass in order to return. So sadly I don't think isTitleTruncated() will work for me.

Does anyone know how else this can be achieved?

Update: I have been playing around with DisplayMetrics and may have found a possible, albeit inconsistent solution.

I can get the width of a device in pixels by:

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int width = displayMetrics.widthPixels;

And then I can get the width of the title string by:

Paint paint = new Paint();
float scaledPx = 18 * displayMetrics.density;
paint.setTextSize(scaledPx);
float stringSize = paint.measureText(username + "  " + "❤" + " " + String.valueOf(rating));

And then I if I divide the string width by the device width, I can find out what percentage of the screen width the string occupies. With a bit of trial and error I can work out and what percentage a title truncates.

I've so far tried this on three devices and unfortunately this number isn't very consistent (truncation has been occurring from 30% to 45% for my app).

I am not very happy with this solution and feel like there must be more reliable methods of working this out.

1 Answers
Related