I tried different combinations in xml file:
MyActivity.java:
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.my_menu, menu);
View view = menu.findItem(R.id.whats_this).getActionView();
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do something
}
});
return super.onCreateOptionsMenu(menu);
}
my_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MyActivity">
<item
android:id="@+id/item"
app:actionLayout="@layout/my_layout"
android:orderInCategory="100"
android:title="@string/whats_this"
app:showAsAction="always" />
</menu>
my_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="30dp"
android:paddingLeft="5dp"
android:gravity="center_vertical"
android:textStyle="bold"
android:textColor="@color/white"
android:text="@string/whats_this"/>
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:src="@mipmap/question"/>
</LinearLayout>
You can use following code for establishing your purpose. No need to make it programmatic. You can trick in menu.xml file.
menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/overflowMenu"
android:icon="@drawable/ic_more_vert_white_24dp"
android:title=""
app:showAsAction="always">
<menu>
<item
android:id="@+id/menuWithIconText"
android:icon="@drawable/chosen_icon"
android:title="@string/menu_item_title"
/>
</menu>
</item>
In above code, we've used menu
inside of item
. In inside menu, we've defined our overflow menu which we want with icon. Just remember to use app:showAsAction="always"
in outside item
tag.
Adding to the answer from dev_ry, there is a much smoother way without using reflection by just casting and suppressing the restricted API warning:
import android.support.v7.view.menu.MenuBuilder;
@SuppressLint("RestrictedApi")
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (menu instanceof MenuBuilder) {
((MenuBuilder) menu).setOptionalIconsVisible(true);
}
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}