Android学习笔记——Menu(三)

  • 知识点

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

  • Popup Menu(弹出式菜单)

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

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

                                                              

 

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

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

 1.用PopupMenu的构造器实例化弹出式菜单,需要当前应用的Context和菜单需要固定到的View。

 2.使用MenuInflater填充你的菜单资源到Menu对象中,这个Menu对象是由PopupMenu.getMenu返回的(在API 14和以上 可以用PopupMenu.inflater替代)

 3.调用PopupMenu.show()

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

 1 public void showPopup(View v){
 2         PopupMenu popup = new PopupMenu(this,v);
 3         MenuInflater inflater = popup.getMenuInflater();
 4         inflater.inflate(R.menu.popup, popup.getMenu());
 5         popup.setOnMenuItemClickListener(this);
 6         popup.show();
 7     }
 8 
 9     @Override
10     public boolean onMenuItemClick(MenuItem arg0) {
11         switch (arg0.getItemId()) {
12         case R.id.item1:
13             Toast.makeText(this, "you have clicked the item 1", Toast.LENGTH_LONG).show();
14             break;
15         case R.id.item2:
16             Toast.makeText(this, "you have clicked the item 2", Toast.LENGTH_LONG).show();
17             break;
18         case R.id.item3:
19             Toast.makeText(this, "you have clicked the item 3", Toast.LENGTH_LONG).show();
20             break;
21         default:
22             break;
23         }
24         return false;
25     }
View Code
 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:orientation="vertical"
 6    >
 7 
 8     <TextView
 9         android:layout_width="wrap_content"
10         android:layout_height="wrap_content"
11         android:text="@string/clickMe" 
12         android:onClick="showPopup"
13         android:clickable="true"/>
14     
15     <ImageButton 
16         android:layout_width="wrap_content"
17         android:layout_height="wrap_content"
18         android:src="@drawable/ic_launcher"
19         android:clickable="true"
20         android:onClick="showPopup"  />
21      
22 </LinearLayout>
View Code

posted @ 2014-09-15 11:33  onerepublic  阅读(894)  评论(0编辑  收藏  举报