I am trying to achieve the Menu Item design as shown in the YouTube application screen below. The menu item I am interested in is the action menu item. In this case the (G)
Firstly, you need to create a custom_menu.xml
like this:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/profile"
<!-- this is the magic !!! -->
android:actionLayout="@layout/custom_layout"
android:icon="@drawable/ic_action_profile"
android:title="@string/profile_update"
app:showAsAction="always" />
</menu>
After this, you create a layout file custom_layout.xml
like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginEnd="@dimen/margin_extra_small"
android:background="@drawable/drawable_circle_solid_accent"
android:gravity="center"
android:padding="@dimen/padding_small"
android:text="G"
android:textColor="@color/colorWhite"
android:textSize="@dimen/text_size_normal"
android:textStyle="bold" />
</LinearLayout>
and set this custom_menu.xml
in your activity
.
Output:
Add this in your activity
:
override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
// getting action layout menu item
val menuItemName = menu?.findItem(R.id.menu_name)
// getting Linear Layout from custom layout
val linearLayout = menuItemName?.actionView as LinearLayout
// getting TextView from Linear Layout, i.e., parent of custom layout
val yourTextView = linearLayout.findViewById<TextView>(R.id.your_text_view_id)
// setting the first char of the String name
yourTextView.text = name.substring(0, 1)
return super.onPrepareOptionsMenu(menu)
}