源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2021-12-26 03:25 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Android学习笔记——Menu介绍(三)
知识点 今天继续昨天没有讲完的Menu的学习,主要是Popup Menu的学习。 Popup Menu(弹出式菜单) 弹出式菜单是一种固定在View上的菜单模型。主要用于以下三种情况: 为特定的内容提供溢出风格(overflow-style)的菜单进行操作。 提供其他部分的命令句(command sentence)如Add按钮可以用弹出菜单提供不同的Add的操作。 提供类似于Spinner的下拉式菜单但不保持持久的选择。 [img]http://files.jb51.net/file_images/article/201410/20141013000961.png[/img] [img]http://files.jb51.net/file_images/article/201410/20141013000962.png[/img] 那怎样显示弹出式菜单呢? 如果你在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>
[img]http://files.jb51.net/file_images/article/201410/20141013000963.png[/img] [img]http://files.jb51.net/file_images/article/201410/20141013000964.png[/img] [img]http://files.jb51.net/file_images/article/201410/20141013000965.png[/img]
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部