1

Android入门第34天-Android的Menu组件使用大全

 1 year ago
source link: https://blog.csdn.net/lifetragedy/article/details/128028803
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Android入门第34天-Android的Menu组件使用大全_TGITCIC的博客-CSDN博客_android 菜单栏组件

dbb610bfd93c452eb4121b7d7f1b47ab.png

Android有不同的菜单:

  • 弹出菜单(可自定义样式)
  • Context Menu;

菜单的使用和我们前面说的AlertDialog很像。它可以支持自定义样式、也可以对菜单的点击事件进行绑定。

Android里有几个MainActivity事件可以覆盖,其中有以下几个事件就是用于处理Menu的。

  • onCreateOptionsMenu(Menu menu),在这个方法里如果你使用menu.add就可以实现在Android的手机里右上角的...图标点击出现系统菜单的效果;

  • onOptionsItemSelected(MenuItem item),这个方法里可以进行每个系统菜单项点击的处理事件;

  • onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) ,这个是用来创建ContextMenu的,即这个菜单可以绑定在一个组件上,比如说按一下一个组件,对于这个组件的菜单就会被弹出。但是它要启作用必须在程序运行开始时调用一下Activity里的自带方法:registerForContextMenu(View view);来指定,ContextMenu绑定在哪个组件的身上;

  • onContextItemSelected(MenuItem item),相应的对于ContextMenu的每一个item的点击处理方法,用户可以自定义和覆盖里面的逻辑;

  1. 做一个可以改变屏幕中间TextView字体颜色的系统菜单;
  2. 点一下按钮弹出一个PopMenu;
  3. 对于一个TextView绑定一个ContextMenu;
9140eddcaa674d3492de3838b46b81e9.png

activity_main.xml

newCodeMoreWhite.png

MainActivity.java

系统菜单涉及到两个方法的覆盖,因此只要在这两个方法把系统菜单设上,同时对系统菜单的“选择”事件做出自定义即可,在此我们通过系统菜单改变屏幕中一行字的字体颜色

newCodeMoreWhite.png
dbd73a4796ac45baa9b24f458d116bed.png

前端代码

 后端代码

newCodeMoreWhite.png

ContextMenu

64146a19215a4af386619f8683176161.png

context_menu.xml

我们可以看到这个ContextMenu是绑定在一个TextView上的。

newCodeMoreWhite.png

所以,请各位动一下手自己试试吧。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK