<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_lnrLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context="com.smartify.customizetoolbardemo.MainActivity"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/lnrlayout_toolbar"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
Add a menu to your toolbar
<?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:title="Settings"
android:id="@+id/action_settings"
/>
</menu>
inflate you menu
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.action_menu, menu);
return true;
}
You will get icon of overflow menu then.
Add one button or any view in your lnrlayout_toolbar
Button btn=(Button)findViewById(R.id.btn_menu);
showPopupMenu(btn);
and call below method for showing overlay menu
public void showPopupMenu(View v){
PopupMenu popup = new PopupMenu(this, v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.sub_menu, popup.getMenu());
popup.show();
}
is sub_menu is your menu file that you want to show..
Try this
XML code for menu items create menu resource in res>>menu>>menu_optipn.xml
<item android:id="@+id/new_game"
android:icon="@mipmap/ic_launcher"
android:title="item1"
/>
<item android:id="@+id/help"
android:icon="@mipmap/ic_launcher"
android:title="item2"
android:orderInCategory="0"
/>
MainActivity.Java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_option, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.new_game:
Toast.makeText(this, "Item 1 is selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.help:
Toast.makeText(this, "Item 2 is selected", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.