码迷,mamicode.com
首页 > 移动开发 > 详细

android PopupMenu弹出式菜单的使用

时间:2015-04-09 10:34:45      阅读:1499      评论:0      收藏:0      [点我收藏+]

标签:android   popupmenu   



PopupMenu代表弹出式菜单。他会指定组件上弹出PopupMenu,默认情况下PopupMenu会显示在该组件的下方或者上方,PopupMenu可以增加多个菜单项并且可以为菜单项添加子菜单、

首先在res/menu下编写xml文件my_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:icon="@drawable/ic_launcher"
        android:title="字体">
        <menu>

            <!-- 定义一个单项菜单项 -->
            <group android:checkableBehavior="single" >
                <item
                    android:id="@+id/font_10"
                    android:title="10号字体"/>
                <item
                    android:id="@+id/font_12"
                    android:title="12号字体"/>
                <item
                    android:id="@+id/font_14"
                    android:title="14号字体"/>
                <item
                    android:id="@+id/font_16"
                    android:title="16号字体"/>
                <item
                    android:id="@+id/font_18"
                    android:title="18号字体"/>
            </group>
        </menu>
    </item>
    <!-- 定义一个普通菜单项 -->
    <item
        android:icon="@drawable/fy_d_kf"
        android:title="普通菜单"/>
    <item
        android:icon="@drawable/fy_d_kf2"
        android:title="颜色">
        <menu>

            <!-- 定义一个单项菜单项 -->
            <group>
                <item
                    android:id="@+id/red"
                    android:title="红色"/>
                <item
                    android:id="@+id/blue"
                    android:title="蓝色"/>
                <item
                    android:id="@+id/green"
                    android:title="绿色"/>
            </group>
        </menu>
    </item>

</menu>

在activity中主要的代码如下

public class MainActivity extends Activity {

 private TextView edit;
 private PopupMenu menu;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  edit = (TextView) findViewById(R.id.textView1);
  edit.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View arg0) {
    clickpopuMne(arg0);
   }
  });
 }

 public void clickpopuMne(View v) {
  menu = new PopupMenu(this, v);
  getMenuInflater().inflate(R.menu.my_menu, menu.getMenu());
  menu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
   
   @Override
   public boolean onMenuItemClick(MenuItem arg0) {
    switch (arg0.getItemId()) {
    case R.id.font_10:
     menu.dismiss();
     break;
    default:
     Toast.makeText(MainActivity.this, ""+arg0.getTitle(), Toast.LENGTH_SHORT).show();
    }
    return true;
   }
  });
  menu.show();
 }
}


android PopupMenu弹出式菜单的使用

标签:android   popupmenu   

原文地址:http://blog.csdn.net/aimingkun/article/details/44956199

(1)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!