Android开发笔记(9)——初步设置Menu

 
初步设置Menu
 
设置Menu,在ActionBar上添加按钮操作:
        main/res目录下添加menu文件夹,创建main.xml文件
    <menu  xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app=" http://schemas.android.com/apk/res/tool">

            <item
                     android:id ="@+id/coffee_cart"
                     android:icon="@drawble/cart"
                     android:title="Delete"
                     app:showAsAction=”always”/>
    </menu>

    

showAsAction属性共有五个值:ifRoomneveralwayswithTextcollapseActionView

ifRoom                      会显示在Item中,依据屏幕的宽窄而定   
never                        永远不会显示。只会在溢出列表中,只显示标题,所以在定义item的时候,最好把标题都带上。   
always                      无论是否溢出,总会显示。   
withText                    withText值显示文本标题。如果图标有效且受到空间的限制,文本标题有可能显示不全。   
collapseActionView   被折叠到一个按钮中,当用户选择时操作视窗展开。一般要配合ifRoom使用才有效果

 
在MainActivity中需要改写onCreateOptionsMenu函数
 
    @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.activity_main, menu);
            return true;
        }
设置点击按钮函数
item.getItemId()获取点击按钮的ID
由于对各个item设独特ID,使用switch-case-default语句判断,并执行命令
 
    @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch(item.getItemId()){
               case R.id. coffee_cart:            
                   Toast.makeText(this, "CoffeeCart", Toast.LENGTH_SHORT).show(); }
            }
 

 
申明:

1、本笔记为文字及图片均为个人原创,转载请注明博客园-igoslly

2、Android开发课程于2017年4年参与GoogleDeveloper进行学习,笔记原版http://www.studyjamscn.com/thread-20580-1-1.html#pid272486

     
 
原文地址:https://www.cnblogs.com/igoslly/p/6858656.html