Menu bar in android studio project

本秂侑毒 提交于 2020-01-07 07:41:52

问题


I'm new to Android Studio and I'm having many problems doing a menubar. I have searched for many solutions but they weren't going right.

I tried this but I don't know what to do next:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    @Override
    public boolean onCreateOptionsMenu (Menu menu) {
        super.onCreateOptionsMenu(menu);
        //Inflate the menu; this adds item to the action
        //bar if its present
        getMenuInflater().inflate(R.menu.my_context_menu, menu);
        String title = "Item Three";
        int groupId = Menu.NONE;
        int itemID = MENU_ITEM;
        int order = 103;
        menu.add(groupId, itemId, order, title);
        return true;
    }

回答1:


First create a main_menu.xml file in your menu rescource folder (or any other...) :

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/one"
        android:title="Button 1"/>
    <item android:id="@+id/two"
        android:title="Button 2"/>
</menu>

Then

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
        case R.id.one:
            // do something
            return true;

        case R.id.two:
            //do something
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}


来源:https://stackoverflow.com/questions/36940981/menu-bar-in-android-studio-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!