GVKun编程网logo

Android 选项菜单Option Menu 使用(android菜单menu实现)

6

对于Android选项菜单OptionMenu使用感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍android菜单menu实现,并为您提供关于android4.0menuoption按键问题、

对于Android 选项菜单Option Menu 使用感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍android菜单menu实现,并为您提供关于android 4.0 menu option 按键问题、android Menu 选项菜单示例、Android onCreateOptionsMenu onPrepareOptionsMenu、Android Option Menu的有用信息。

本文目录一览:

Android 选项菜单Option Menu 使用(android菜单menu实现)

每个Activity都可以有至多一个选项菜单
菜单的视图文件最好在res下再新建一个目录存放,菜单视图文件名就是一个菜单资源标识

选项菜单的创建和使用

xml部分

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:title="登录"
        android:id="@+id/login"
        />
    <item android:title="注册"
        android:id="@+id/register"
        />
    <item android:title="其他">
        <menu>
            <item android:title="系统更新"/>
            <item android:title="设置"/>
            <item android:title="关于"/>
        </menu>
    </item>
</menu>

java部分

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // 初始化加载菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // MenuInflater是菜单xml文件的加载器,用它解析xml代码并加载到当前的menu对象中
        MenuInflater ml = getMenuInflater();

        // 第一个参数  menu的xml文件资源   第二个参数  当前的menu对象
        ml.inflate(R.menu.option, menu);

        // 必须返回true,否则菜单将不会显示
        return true;
    }

    // 选项菜单 菜单项监听器
    @Override
    public boolean onoptionsItemSelected(MenuItem item) {

        // 定位到每个菜单项
        switch (item.getItemId()) {
            case R.id.login:
                Toast.makeText(this, "你刚刚点了登录", Toast.LENGTH_LONG).show();
                break;
            case R.id.register:
                Toast.makeText(this, "你刚刚点了注册", Toast.LENGTH_LONG).show();
                break;
            // 此处默认指向父类实现
            default:
                super.onoptionsItemSelected(item);
        }
        return true;
    }
}

android 4.0 menu option 按键问题

关于4.0之后版本,想详细的了解下底下那一排按键,back ,home ,recent_apps ,menu,这几个按键是怎么控制的,比如 menu按键,在某些界面是隐藏的,在某些界面是显示出来的,这是通过什么控制的,而他们执行的功能都是opiton的功能。请知道的告诉下。万分感谢!

android Menu 选项菜单示例

ch7_menu.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="这是一个选项菜单和子菜单的示例"/>
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tv"
        android:textSize="20px"/>

</LinearLayout>

MenuActivity.java :

package com.example.ch7;

import com.example.baseexample.R;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.widget.TextView;

public class MenuActivity extends Activity {
	private TextView tv;
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);;
		setContentView(R.layout.ch7_menu);
		
	}
	
	public boolean onCreateOptionsMenu(Menu menu){
		SubMenu sub = menu.addSubMenu(Menu.NONE,Menu.FIRST,0,"发送").setIcon(android.R.drawable.ic_menu_send);
		sub.add(Menu.NONE,Menu.FIRST+6,6,"发送到蓝牙");
		sub.add(Menu.NONE,Menu.FIRST+7,7,"发送到微博");
		sub.add(Menu.NONE,Menu.FIRST+8,8,"发送到E-mail");
		menu.add(Menu.NONE,Menu.FIRST+1,1,"保存").setIcon(android.R.drawable.ic_menu_edit);
		menu.add(Menu.NONE,Menu.FIRST+2,2,"帮助").setIcon(android.R.drawable.ic_menu_help);
		menu.add(Menu.NONE,Menu.FIRST+3,3,"添加").setIcon(android.R.drawable.ic_menu_add);
		menu.add(Menu.NONE,Menu.FIRST+4,4,"详细").setIcon(android.R.drawable.ic_menu_info_details);
		menu.add(Menu.NONE,Menu.FIRST+5,5,"退出").setIcon(android.R.drawable.ic_menu_delete);
		
		return true;
		
	}
	
	public boolean onOptionsItemSelected(MenuItem item){
		tv=(TextView)findViewById(R.id.tv);
		switch(item.getItemId()){
		case Menu.FIRST:
			tv.setText("你点击了发送菜单");
			break;
		case Menu.FIRST+1:
			tv.setText("你点击了保存菜单");
			break;
		case Menu.FIRST+2:
			tv.setText("你点击了帮助菜单");
			break;
		case Menu.FIRST+3:
			tv.setText("你点击了添加菜单");
			break;
		case Menu.FIRST+4:
			tv.setText("你点击了详细菜单");
			break;
		case Menu.FIRST+5:
			tv.setText("你点击了退出菜单");
			break;
		case Menu.FIRST+6:
			tv.setText("你点击了发送到蓝牙");
			break;
		case Menu.FIRST+7:
			tv.setText("你点击了发送到微博");
			break;
		case Menu.FIRST+8:
			tv.setText("你点击了发送到E-mail");
			break;
		}
		return super.onOptionsItemSelected(item);
	}
}


Android onCreateOptionsMenu onPrepareOptionsMenu

Android onCreateOptionsMenu onPrepareOptionsMenu

异步刷新menu :getActivity().supportInvalidateOptionsMenu();


onPrepareOptionsMenu

每次访问都重新填充菜单项


onCreateOptionsMenu 



1. onPrepareOptionsMenu()调用时机。

一般情况下,每次按menu键Framewrok都会先调用onPrepareOptionsMenu(),准备需要显示的菜单。但是当按menu键之前调用了Activity.invalidateOptionsMenu()之后,情况变的不一样,调用完Activity.invalidateOptionsMenu()之后,Framework会立即调用onPrepareOptionsMenu()准备好菜单项数据,之后当用户按menu键时,Framework不会再次调用onPrepareOptionsMenu(),而是将之前准备好的菜单显示出来。这点一定要注意。

2. 清除之前的menu数据。

每次调用onPrepareOptionsMenu()的时候需要首先调用menu.clear()清除一下之前的menu数据,如果不清除的话,之前的menu数据不会被释放,造成内存泄漏。





1、复写onPrepareOptionsMenu方法

 

@Override
 public void onPrepareOptionsMenu(Menu menu) {
  

  menu.clear();//先清除已经建好的menu


  MenuInflater inflater = getActivity().getMenuInflater();

//根据各种条件,重新设置menu

  if (isDeleteIconOnActionBar){
   inflater.inflate(R.menu.delete_action, menu);   
  }else if(isRefreshIconOnActionBar){ 
   inflater.inflate(R.menu.delete_refresh_action, menu);
  }else{
   inflater.inflate(R.menu.main_activity_actions, menu);
  }
  super.onPrepareOptionsMenu(menu);
 }

 

2、在需要修改menu的地方调用

getActivity().supportInvalidateOptionsMenu();




Android Option Menu

Creating an Options Menu

Figure 1. Options menu in the Browser, on Android 2.3.

The options menu is where you should include actions and other options that are relevant to the current activity context, such as "Search," "Compose email," and "Settings."

Where the items in your options menu appear on the screen depends on the version for which you''ve developed your application:

  • If you''ve developed your application for Android 2.3.x (API level 10) or lower, the contents of your options menu appear at the bottom of the screen when the user presses the Menu button, as shown in figure 1. When opened, the first visible portion is the icon menu, which holds up to six menu items. If your menu includes more than six items, Android places the sixth item and the rest into the overflow menu, which the user can open by selectingMore.
  • If you''ve developed your application for Android 3.0 (API level 11) and higher, items from the options menu are available in the action bar. By default, the system places all items in the action overflow, which the user can reveal with the action overflow icon on the right side of the action bar (or by pressing the device Menu button, if available). To enable quick access to important actions, you can promote a few items to appear in the action bar by addingandroid:showAsAction="ifRoom" to the corresponding <item> elements (see figure 2).

    For more information about action items and other action bar behaviors, see the Action Bar guide.

    Note: Even if you''re not developing for Android 3.0 or higher, you can build your own action bar layout for a similar effect. For an example of how you can support older versions of Android with an action bar, see the Action Bar Compatibility sample.

Figure 2. Action bar from the Honeycomb Gallery app, showing navigation tabs and a camera action item (plus the action overflow button).

You can declare items for the options menu from either your Activity subclass or a Fragment subclass. If both your activity and fragment(s) declare items for the options menu, they are combined in the UI. The activity''s items appear first, followed by those of each fragment in the order in which each fragment is added to the activity. If necessary, you can re-order the menu items with the android:orderInCategory attribute in each <item> you need to move.

To specify the options menu for an activity, override onCreateOptionsMenu() (fragments provide their own onCreateOptionsMenu() callback). In this method, you can inflate your menu resource (defined in XML) into the Menu provided in the callback. For example:

@Override public boolean onCreateOptionsMenu(Menu menu) {     MenuInflater inflater = getMenuInflater();     inflater.inflate(R.menu.game_menu, menu);     return true; }

You can also add menu items using add() and retrieve items with findItem() to revise their properties with MenuItem APIs.

If you''ve developed your application for Android 2.3.x and lower, the system calls onCreateOptionsMenu() to create the options menu when the user opens the menu for the first time. If you''ve developed for Android 3.0 and higher, the system calls onCreateOptionsMenu() when starting the activity, in order to show items to the action bar.

Handling click events

When the user selects an item from the options menu (including action items in the action bar), the system calls your activity''s onOptionsItemSelected() method. This method passes the MenuItem selected. You can identify the item by calling getItemId(), which returns the unique ID for the menu item (defined by the android:id attribute in the menu resource or with an integer given to the add() method). You can match this ID against known menu items to perform the appropriate action. For example:

@Override public boolean onOptionsItemSelected(MenuItem item) {     // Handle item selection     switch (item.getItemId()) {         case R.id.new_game:             newGame();             return true;         case R.id.help:             showHelp();             return true;         default:             return super.onOptionsItemSelected(item);     } }

When you successfully handle a menu item, return true. If you don''t handle the menu item, you should call the superclass implementation of onOptionsItemSelected() (the default implementation returns false).

If your activity includes fragments, the system first calls onOptionsItemSelected() for the activity then for each fragment (in the order each fragment was added) until one returnstrue or all fragments have been called.

Tip: Android 3.0 adds the ability for you to define the on-click behavior for a menu item in XML, using the android:onClick attribute. The value for the attribute must be the name of a method defined by the activity using the menu. The method must be public and accept a single MenuItem parameter—when the system calls this method, it passes the menu item selected. For more information and an example, see the Menu Resource document.

Tip: If your application contains multiple activities and some of them provide the same options menu, consider creating an activity that implements nothing except the onCreateOptionsMenu() and onOptionsItemSelected() methods. Then extend this class for each activity that should share the same options menu. This way, you can manage one set of code for handling menu actions and each descendant class inherits the menu behaviors. If you want to add menu items to one of the descendant activities, override onCreateOptionsMenu() in that activity. Call super.onCreateOptionsMenu(menu) so the original menu items are created, then add new menu items with menu.add(). You can also override the super class''s behavior for individual menu items.

今天关于Android 选项菜单Option Menu 使用android菜单menu实现的讲解已经结束,谢谢您的阅读,如果想了解更多关于android 4.0 menu option 按键问题、android Menu 选项菜单示例、Android onCreateOptionsMenu onPrepareOptionsMenu、Android Option Menu的相关知识,请在本站搜索。

本文标签: