在res下创建目录menu(假设已经有啦就不用再创建了)
在该menu目录下创建XML文件这里我把文件名称命名为menu
在创建的menu.XML文件里
写入:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/file"
android:title="file"/>
<item
android:id="@+id/edit"
android:title="edit"/>
<item
android:id="@+id/help"
android:title="help">
<menu>
<item
android:id="@+id/window"
android:title="window"/>
<item
android:id="@+id/run"
android:title="run"/>
</menu>
</item>
</menu>
在Activity中创建菜单的地方把以下的代码换成this.getMenuInflater().inflate(R.menu.menu,menu);
R.menu.menu代表你创建的菜单XML文件
menu.add("file");
menu.add("edit");
menu.add("source");
即:
public class MainActivity extends Activity {
private TextView username,password;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (TextView) findViewById(R.id.username);
password = (TextView) findViewById(R.id.password);
this.registerForContextMenu(username);//注冊菜单
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
this.getMenuInflater().inflate(R.menu.menu,menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
//当菜单上下文元素被选中时运行
Toast.makeText(this, item.getTitle()+"onContextItemSelected",
1).show();
return super.onContextItemSelected(item);
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item)
{
// TODO Auto-generated method stub
//菜单元素被选中时运行
Toast.makeText(this, item.getTitle()+"onMenuItemSelected",
1).show();
return super.onMenuItemSelected(featureId, item);
}
}