How to calculate back button width, tootlbar title width and menu item width in android?

Viewed 123

I have a custom toolbar that shows the toolbar title and an image? The issue here is the image sometimes goes behind menu items or it goes out of the screen?

So I am doing a calculation where:

int width_remaining_for_toolbar_title = screen_width - back_button_width - image_width(assuming its loaded) - (no of menu items * menu_item_width)

width_required = paint.measure(toolbar_title_string)
if(width_required < width_remaining)

then show image else remove the image. https://i.stack.imgur.com/knRxc.png

Usage:

<androidx.appcompat.widget.Toolbar
  android:id="@+id/toolbar"
  style="@style/TitleStyle"
  android:layout_width="match_parent"
  android:layout_height="?attr/actionBarSize"
  app:layout_collapseMode="pin">
  <TextView
    android:id="@+id/tv_toolbar"
    style="@style/Heading2"
    android:gravity="center_vertical"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:ellipsize="end"
    android:layout_marginRight="@dimen/grid_2"
    android:maxLines="1"
    android:text="" />
  <include layout="@layout/image"/>
</androidx.appcompat.widget.Toolbar>

How can I get back button width, toolbar title width, and menu item width or is there a better way to solve this problem?

0 Answers
Related