android 自訂菜單 使用PopupWindow實現菜單的各種效果

來源:互聯網
上載者:User

       隨著android手機的不斷髮展,可以在android手機上實現的菜單方式有多種多樣,不同的開發人員實現的效果也不一樣;想要在android手機上調用菜單,方式也是多種多樣的,在此列舉三類調用菜單的方式:

1、使用ActionBar上“更多”按鈕調用菜單(在“檔案”項目中定義了二級菜單目錄),

  

2、自訂按鈕調用菜單,


3、使用手機物理按鍵"menu"調用菜單(部分手機可能無此按鍵),在圖中顯示了兩個菜單列表,一個是自訂的菜單列表,一個是使用系統Menu添加的菜單列表,在onMenuOpened()方法中設定相應的返回值(true/false)可以控制是否開啟menu菜單列表,

以上三類型的菜單顯示為本人總結的方法,當然也有其他很多方法能夠實現,具體的實現效果,就要根據具體的需求而定了。


下面我們來看看怎麼實現的,首先定義一個ActionBar上的菜單列表布局檔案res/menu/main.xml,若沒有該檔案或檔案夾可自行建立

<menu xmlns:android="http://schemas.android.com/apk/res/android" >    <item        android:id="@+id/action_settings"        android:orderInCategory="100"        android:showAsAction="always"        android:icon="@drawable/ic_menu_overflow">        <menu >            <item                 android:id="@+id/action_edit"                android:showAsAction="always"                android:icon="@drawable/ic_edit"                android:title="@string/edit_text"/>            <item                 android:id="@+id/action_file"                android:showAsAction="always"                android:icon="@drawable/ic_menu_file"                android:title="@string/file">                <!-- file的二級目錄 -->                <menu>            <item                 android:id="@+id/action_share"                android:showAsAction="always"                android:icon="@drawable/ic_menu_share_holo_light"                android:title="@string/share"/>            <item                 android:id="@+id/action_favorite"                android:showAsAction="always"                android:icon="@drawable/ic_menu_star_holo_light"                android:title="@string/favorite"/>                </menu>            </item>            <item                android:id="@+id/action_about"                android:showAsAction="always"                android:icon="@drawable/ic_menu_about"                android:title="@string/about"/>        </menu>        </item></menu>
第一個Item是用來放在ActionBar上的入口,通過這個入口可以調用我們定義的功能表列;

屬性介紹:

  • showAsAction:設定ActionBar中menu的顯示方式
  • icon:item上的表徵圖
  • title:文本資訊

然後我們需要在自訂一個下拉式功能表布局檔案

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:orientation="vertical"    android:background="@drawable/bitmap_book_read_chapterlist_repeat" >    <TextView         android:id="@+id/textview_edit"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:drawableLeft="@drawable/ic_edit"        android:text="@string/edit_text"        android:gravity="center_vertical"        android:textColor="#ff0000"/>    <TextView         android:id="@+id/textview_file"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:drawableLeft="@drawable/ic_menu_file"        android:text="@string/file"        android:gravity="center_vertical"        android:textColor="#ff0000"/>    <TextView         android:id="@+id/textview_about"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:drawableLeft="@drawable/ic_menu_about"        android:text="@string/about"        android:gravity="center_vertical"        android:textColor="#ff0000"/></LinearLayout>

布局檔案內容大致介紹一下,設定了整個view的一個背景,定義了三個TextView用來顯示菜單的內容,在java代碼裡面也實現了三個按鈕的點擊事件。

然後,我在自訂的下拉式功能表上實現了一個漸進漸出的動畫效果,代碼很簡單

漸入動畫popup_window_enter.xml


<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android">    <translate android:fromYDelta="100%p" android:toYDelta="0" android:duration="1000"/>    <alpha android:fromAlpha="0" android:toAlpha="1.0" android:duration="1000"/></set>

漸齣動畫popup_window_exit.xml

<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android">    <translate android:fromXDelta="0" android:toXDelta="100%p" android:duration="1000"/>    <alpha android:fromAlpha="1.0" android:toAlpha="0" android:duration="1000"/></set>

下面就進入主題了,如何在代碼中實現整個menu效果MainActivity.java

package com.example.menutype;import android.app.ActionBar.LayoutParams;import android.app.Activity;import android.content.Context;import android.os.Bundle;import android.view.Gravity;import android.view.LayoutInflater;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.PopupWindow;import android.widget.PopupWindow.OnDismissListener;import android.widget.TextView;import android.widget.Toast;/** *  * @author tr * @time 2014-3-10 * @description 自訂菜單,下拉式功能表樣式,添加動畫效果,重寫onMenuOpened()方法,自訂"menu"按鍵快顯功能表 */public class MainActivity extends Activity implements OnClickListener{private static Toast mToast;private static Context mContext;private PopupWindow popupWindow ;private Button btn_popupwindow;private View mPopupWindowView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mContext = this;btn_popupwindow = (Button) findViewById(R.id.btn_popupwindow);btn_popupwindow.setOnClickListener(this);initPopupWindow();}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {/**actionBar上更多按鈕*/getMenuInflater().inflate(R.menu.main, menu);/**點擊menu,快顯功能表*/        /*         *          * add()方法的四個參數,依次是:         *          * 1、組別,如果不分組的話就寫Menu.NONE,         *          * 2、Id,這個很重要,Android根據這個Id來確定不同的菜單         *          * 3、順序,那個菜單現在在前面由這個參數的大小決定         *          * 4、文本,菜單的顯示文本         */        menu.add(Menu.NONE, Menu.FIRST + 1, 1, getResource(R.string.edit_text)).setIcon(        R.drawable.ic_edit);        // setIcon()方法為菜單設定表徵圖,這裡使用的是系統內建的表徵圖,同學們留意一下,以        // android.R開頭的資源是系統提供的,我們自己提供的資源是以R開頭的        menu.add(Menu.NONE, Menu.FIRST + 2, 2, getResource(R.string.file)).setIcon(        R.drawable.ic_menu_file);        menu.add(Menu.NONE, Menu.FIRST + 3, 3, getResource(R.string.about)).setIcon(        R.drawable.ic_menu_about);return true;}/**菜單開啟時調用*/@Overridepublic boolean onMenuOpened(int featureId, Menu menu) {// TODO Auto-generated method stubshowToast("menu菜單開啟:"+featureId);//點擊"menu"按鈕開啟if(featureId == 0){showPopupWindow();}return super.onMenuOpened(featureId, menu);// 返回為true 則顯示系統menu//return false;}/**menu菜單關閉時調用*/@Overridepublic void onOptionsMenuClosed(Menu menu) {// TODO Auto-generated method stubsuper.onOptionsMenuClosed(menu);showToast("menu菜單關閉");}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {// TODO Auto-generated method stubswitch(item.getItemId()){case Menu.FIRST + 1:case R.id.action_edit:showToast(getResource(R.string.edit_text));break;case Menu.FIRST + 2:case R.id.action_file:showToast(getResource(R.string.file));break;case R.id.action_favorite:showToast(getResource(R.string.favorite));break;case R.id.action_share:showToast(getResource(R.string.share));break;case Menu.FIRST + 3:case R.id.action_about:showToast(getResource(R.string.about));break;}return super.onOptionsItemSelected(item);}@Overridepublic void onClick(View v) {switch(v.getId()){case R.id.btn_popupwindow:showPopupWindow();break;case R.id.textview_about:showToast(getResource(R.string.about));popupWindow.dismiss();break;case R.id.textview_edit:showToast(getResource(R.string.edit_text));popupWindow.dismiss();break;case R.id.textview_file:showToast(getResource(R.string.file));popupWindow.dismiss();break;}}/**顯示popupwindow*/private void showPopupWindow(){if(!popupWindow.isShowing()){popupWindow.showAsDropDown(btn_popupwindow, btn_popupwindow.getLayoutParams().width/2, 0);}else{popupWindow.dismiss();}}/** * 初始化popupwindow */private void initPopupWindow(){initPopupWindowView();//初始化popupwindow,綁定顯示view,設定該view的寬度/高度popupWindow = new PopupWindow(mPopupWindowView,LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);popupWindow.setFocusable(true);popupWindow.setOutsideTouchable(true);// 這個是為了點擊“返回Back”也能使其消失,並且並不會影響你的背景;使用該方法點擊表單之外,才可關閉表單popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.bitmap_book_read_chapterlist_repeat));//Background不能設定為null,dismiss會失效//popupWindow.setBackgroundDrawable(null);//設定漸入、漸齣動畫效果//popupWindow.setAnimationStyle(R.style.popupwindow);popupWindow.update();//popupWindow調用dismiss時觸發,設定了setOutsideTouchable(true),點擊view之外/按鍵back的地方也會觸發popupWindow.setOnDismissListener(new OnDismissListener() {@Overridepublic void onDismiss() {// TODO Auto-generated method stub//showToast("關閉popupwindow");}});}/** * 初始化popupwindowView,監聽view中的textview點擊事件 */private void initPopupWindowView(){mPopupWindowView = LayoutInflater.from(mContext).inflate(R.layout.popupwindowmenu, null);TextView textview_edit = (TextView) mPopupWindowView.findViewById(R.id.textview_edit);textview_edit.setOnClickListener(this);TextView textview_file = (TextView) mPopupWindowView.findViewById(R.id.textview_file);textview_file.setOnClickListener(this);TextView textview_about = (TextView) mPopupWindowView.findViewById(R.id.textview_about);textview_about.setOnClickListener(this);}/**擷取string.xml資源*/public String getResource(int id){return getResources().getString(id);}/**Toast單例模式*/public static Toast getInstance(){if(mToast == null){mToast = Toast.makeText(mContext, "", Toast.LENGTH_LONG);mToast.setGravity(Gravity.CENTER, 0, 0);}return mToast;}/**顯示toast*/public void showToast(String str){Toast toast = getInstance();toast.setText(str);toast.show();}}

原始碼,點擊下載


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.