How to add a menu to the layout

I have a situation where there are different layouts, and each layout has a menu. How should I do it? For reference, you can visit the Youtube Mobile App and on the right side of the video, 3 dots appear, clicking on them opens a menu. I have a screenshot, but inadequate loans do not allow me to upload it. Please help me. Thanks at Advance.!

+4
source share
2 answers

Remember, you do not need to design a design layout for the action bar.

just create the file @ res / menu / main_activity_actions.xml and add the item you want to use in the action bar.

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/action_search"
      android:icon="@drawable/ic_action_search"
      android:title="@string/action_search"/>
<item android:id="@+id/action_compose"
      android:icon="@drawable/ic_action_compose"
      android:title="@string/action_compose" />

Click layout oncreateoption menu

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu items for use in the action bar
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_activity_actions, menu);
    return super.onCreateOptionsMenu(menu);
}

Handle click events for items.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle presses on the action bar items
    switch (item.getItemId()) {
        case R.id.action_search:
            openSearch();
            return true;
        case R.id.action_compose:
            composeMessage();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
+6

1632209, Android, , :

PopupMenu popup = new PopupMenu(context, btnSettings); //you can use image button
                                          // as btnSettings on your GUI after 
                                  //clicking this button pop up menu will be shown

popup.getMenuInflater().inflate(R.menu.settings_menu, popup.getMenu());
popup.setOnMenuItemClickListener(this);
        popup.show();

, :

@Override
    public boolean onMenuItemClick(MenuItem item) {

        switch (item.getItemId()) {
        case R.id.option1:
            //Code for option 1
            break;

        case R.id.option2:
            //Code for option 2
            break;

        default:
            break;
        }
        return false;
    }

settings_menu.xml res- > menu, :

<item
    android:id="@+id/option1"
    android:icon="@drawable/icon_for_option1"
    android:orderInCategory="100"
    android:showAsAction="never"
    android:title="Option 1"/>

<item
    android:id="@+id/option2"
    android:icon="@drawable/icon_for_option1"
    android:orderInCategory="200"
    android:showAsAction="never"
    android:title="Option 2"/>

+1

Source: https://habr.com/ru/post/1548016/


All Articles