在Android studio中,首先在res包下,右键New->Android resource directory,并以menu命名文件夹的名字;右键menu文件夹->Menu resource file选项,创建main_menu.xml文件。
menu.xml代码:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/one"
android:showAsAction="always"
android:title="开始"
/>
<item
android:id="@+id/two"
android:showAsAction="always"
android:title="结束"
/>
<item
android:id="@+id/three"
android:showAsAction="always"
android:title="设置"
>
<menu >
<item
android:id="@+id/grade"
android:title="年级设置" />
<item
android:id="@+id/classes"
android:title="班级设置" />
</menu>
</item> // 要在item中嵌套子菜单时,item的书写形式
</menu>
MainActivity.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.lenovo.myapplication.MainActivity"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="helloworld"/>
</LinearLayout>
java代码:
package com.example.lenovo.myapplication;
import android.content.ClipData;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
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){
getMenuInflater().inflate(R.menu.classfive,menu);//使得菜单xml显示出来
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)//菜单的点击事件
{
super.onOptionsItemSelected(item);
switch (item.getItemId())
{
case R.id.one:
Toast.makeText(this,"开始",Toast.LENGTH_LONG);
break;
case R.id.two:
Toast.makeText(this,"结束",Toast.LENGTH_LONG);
break;
case R.id.three:
Toast.makeText(this,"设置",Toast.LENGTH_LONG);
break;
case R.id.grade:
Toast.makeText(this,"年级设置",Toast.LENGTH_LONG);
break;
case R.id.classes:
Toast.makeText(this,"班级设置",Toast.LENGTH_LONG);
break;
}
return true;
}
}