·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> Android开发 >> Android学习笔记——Menu介绍(三)

Android学习笔记——Menu介绍(三)

作者:佚名      Android开发编辑:admin      更新时间:2022-07-23

知识点

今天继续昨天没有讲完的Menu的学习,主要是Popup Menu的学习。

Popup Menu(弹出式菜单)

弹出式菜单是一种固定在View上的菜单模型。主要用于以下三种情况:

为特定的内容提供溢出风格(overflow-style)的菜单进行操作。
提供其他部分的命令句(command sentence)如Add按钮可以用弹出菜单提供不同的Add的操作。
提供类似于Spinner的下拉式菜单但不保持持久的选择。

那怎样显示弹出式菜单呢?

如果你在XML文件中定义了菜单,那么以下三步就可显示:

 1.用PopupMenu的构造器实例化弹出式菜单,需要当前应用的Context和菜单需要固定到的View。
 2.使用MenuInflater填充你的菜单资源到Menu对象中,这个Menu对象是由PopupMenu.getMenu返回的(在API 14和以上 可以用PopupMenu.inflater替代)
 3.调用PopupMenu.show()

 下面通过一个例子来理解PopupMenu的使用:

public void showPopup(View v){
    PopupMenu popup = new PopupMenu(this,v);
    MenuInflater inflater = popup.getMenuInflater();
    inflater.inflate(R.menu.popup, popup.getMenu());
    popup.setOnMenuItemClickListener(this);
    popup.show();
  }

  @Override
  public boolean onMenuItemClick(MenuItem arg0) {
    switch (arg0.getItemId()) {
    case R.id.item1:
      Toast.makeText(this, "you have clicked the item 1", Toast.LENGTH_LONG).show();
      break;
    case R.id.item2:
      Toast.makeText(this, "you have clicked the item 2", Toast.LENGTH_LONG).show();
      break;
    case R.id.item3:
      Toast.makeText(this, "you have clicked the item 3", Toast.LENGTH_LONG).show();
      break;
    default:
      break;
    }
    return false;
  }
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  >

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/clickMe" 
    android:onClick="showPopup"
    android:clickable="true"/>
  
  <ImageButton 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_launcher"
    android:clickable="true"
    android:onClick="showPopup" />
   
</LinearLayout>