【Android 开发教程】上下文菜单
来源:互联网 发布:淘宝买玩具枪犯法吗 编辑:程序博客网 时间:2024/06/04 20:33
本章节翻译自《Beginning-Android-4-Application-Development》,如有翻译不当的地方,敬请指出。
原书购买地址http://www.amazon.com/Beginning-Android-4-Application-Development/dp/1118199545/在上一节,我们已经知道了在按MENU键的时候,如何显示选项菜单。但是,除了选项菜单,你也可以显示一个上下文菜单。上下文菜单通常是和activity中的组件相关联的。当用户长按一个组件的时候,它的上下文菜单就会被触发。例如,用户长按一个Button,一个上下文菜单就有可能被显示。
如果想要把一个组件与一个上下文菜单联系在一起,就需要在组件上面调用setOnCreateContextMenuListener()。
下面展示如何显示一个上下文菜单(Context Menu)。
1. 使用之前的工程,修改main.xml。
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:id="@+id/button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Click and hold on it" /></LinearLayout>
2. 在MenusActivity.java中添加一些代码。
public class MenusActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button btn = (Button) findViewById(R.id.button1); btn.setOnCreateContextMenuListener(this); } @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, view, menuInfo); CreateMenu(menu); } @Override public boolean onCreateOptionsMenu(Menu menu) { ...... } @Override public boolean onOptionsItemSelected(MenuItem item) { return MenuChoice(item); } private void CreateMenu(Menu menu) { ...... } private boolean MenuChoice(MenuItem item) { ...... }}
3. 按F11在模拟器上面调试。当点击Button并维持一段时间后,上下文菜单显出出来了。
在上面的例子中,我们调用了button的setOnCreateContextMenuListener()方法,是button与上下文菜单关联到了一起。
当上下文菜单中了某一项被点击时,onContextItemSelected()这个方法就会被触发。
注意,上下文菜单中的快捷键是不起作用的。如果想要使快捷键起作用,需要调用setQuertyMode()方法。
private void CreateMenu(Menu menu) { menu.setQwertyMode(true); MenuItem mnu1 = menu.add(0, 0, 0, "Item 1"); { mnu1.setAlphabeticShortcut('a'); mnu1.setIcon(R.drawable.ic_launcher); } ...... }
- 【Android 开发教程】上下文菜单
- Android开发之创建ContextMenu上下文菜单
- android开发之使用上下文菜单
- android开发中的ContextMneu(上下文菜单)
- Android 上下文菜单实现
- Android 上下文菜单实现
- [android]上下文菜单
- Android--ContextMenu上下文菜单
- Android上下文菜单
- Android 上下文菜单
- android 上下文菜单
- 【Android】上下文菜单contextMenu
- android上下文菜单
- Android上下文菜单 ContextMenu
- Android上下文菜单
- Android-ContextMenu上下文菜单
- Android自定义上下文菜单
- Android上下文菜单
- python编码方式
- java中参数传递
- XP下共享磁盘文件夹方法
- 舌尖上的阳朔,除米粉之外的桂菜诱惑
- 移动应用程序开发应考虑的八大安全问题
- 【Android 开发教程】上下文菜单
- WinScanX
- 帮助你使用数据库方式访问JSON数据的javascript类库-TaffyDB
- 多线程拨号Java版(探讨synchronized和Lock线程同步)
- Android 实现iphone主屏幕文件夹展开合并效果(OpenFolder)
- C++ map学习笔记
- EBS常用命令
- Linux下运行window程序的解决方法
- How to create a Java component with Eclipse