Create a menu simple menu of Android learning

The first hair blog, send a simple practice your hand, first to create a simple menu.

 

First create a menu in the res directory folder, then create a menu file menu file code is as follows:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:id="@+id/item_first"
    android:title="@string/item_name1"
    ></item>
    <item
        android:id="@+id/item_two"
        android:title="@string/item_name2"
        />
</menu>

Then rewrite the onCreateOptionsMenu () method in which MainActivity, can override the shortcut keys Ctrl + O;

//重写方法显示菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main,menu);
        return true;
    }

Then also need to rewrite the onOptionsItemSelected () method is defined in response to an event menu

    //定义菜单响应事件
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
      switch (item.getItemId()){
          case R.id.item_first:
              Toast.makeText(this,"item_first",Toast.LENGTH_SHORT).show();
              break;
          case R.id.item_two:
              Toast.makeText(this,"item_two",Toast.LENGTH_SHORT).show();
              break;
          default:
      }
        return true;
    }

This blog just to reinforce learning

Guess you like

Origin blog.csdn.net/qq_41334474/article/details/80963363