用安卓代码创建一个包含有三个菜单项的菜单,其中一个菜单项设置子菜单。请使用OptionMenu和ContextMenu两种菜单实现
时间: 2024-03-14 21:43:53 浏览: 162
安卓Android源码——ContextMenu上下文选项菜单,长按后跳出菜单.zip
5星 · 资源好评率100%
好的,以下是使用OptionMenu和ContextMenu实现的代码:
OptionMenu实现:
```java
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// 创建菜单
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
// 处理菜单项选择事件
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_new) {
Toast.makeText(this, "New", Toast.LENGTH_SHORT).show();
return true;
} else if (id == R.id.menu_open) {
Toast.makeText(this, "Open", Toast.LENGTH_SHORT).show();
return true;
} else if (id == R.id.menu_save) {
Toast.makeText(this, "Save", Toast.LENGTH_SHORT).show();
return true;
} else if (id == R.id.menu_exit) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
// 创建子菜单
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
SubMenu subMenu = menu.findItem(R.id.menu_edit).getSubMenu();
subMenu.clear();
subMenu.add(0, R.id.menu_cut, 0, "Cut");
subMenu.add(0, R.id.menu_copy, 0, "Copy");
subMenu.add(0, R.id.menu_paste, 0, "Paste");
return super.onPrepareOptionsMenu(menu);
}
}
```
ContextMenu实现:
```java
import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
// 注册上下文菜单
registerForContextMenu(textView);
}
// 创建上下文菜单
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
getMenuInflater().inflate(R.menu.context_menu, menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
// 处理上下文菜单项选择事件
@Override
public boolean onContextItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_cut) {
Toast.makeText(this, "Cut", Toast.LENGTH_SHORT).show();
return true;
} else if (id == R.id.menu_copy) {
Toast.makeText(this, "Copy", Toast.LENGTH_SHORT).show();
return true;
} else if (id == R.id.menu_paste) {
Toast.makeText(this, "Paste", Toast.LENGTH_SHORT).show();
return true;
}
return super.onContextItemSelected(item);
}
}
```
以上两种方法都可以实现包含有三个菜单项的菜单,其中一个菜单项设置了子菜单。OptionMenu适用于菜单栏,ContextMenu适用于上下文菜单。
阅读全文