Menus and popup windows

Source: Internet
Author: User

There are some mechanisms for displaying level two content and activity in the app:
-Context Action module: an action module will start after the user selects an item, and on this option Actionbar the module that transforms into context shows the relevant action.
-Popup Menu Module menu is bound to a view, the menu is displayed below the view, is used to provide overflow of the menu allows two level action.
-Pop-up window when a simple dialog window appears, it gets focus to show additional information
-Conversation fragment a fully customized dialog window appears above the activity, containing all the content defined in the fragment. The most flexible approach, but also very complex

Contextual Action Module

The important action of the associated item should be presented by building an alert action module, which generally appears on a view of a long-press operation or a checkbox selection.

Defined

First, define the XML file for the menures/menu/actions_textview.xml

<menu xmlns...>    <item android:id="@+id/menu_edit"        "Edit"        "@android:drawable/ic_menu_edit"/>    <item android:id="@+id/menu_delete"            "Delete"            android:icon="@android:drawable/ic_menu_delete"/></menu>

Above is the layout of the Actionbar in the context module and then we define the callback function to manage the context menu behavior:

 //define the callback function when Actionmode is activated    PrivateAndroid.view.ActionMode.Callback Modelcallback =NewAndroid.view.ActionMode.Callback () {//When Actionmode is created, call, Startactionmode ()        @Override         Public Boolean Oncreateactionmode(Android.view.ActionMode mode, menu menu) {Mode.settitle ("Actions"); Mode.getmenuinflater (). Inflate (R.menu.actions_viewtext, menu);return true; }//Every time actionmode occurs , it is called        @Override         Public Boolean Onprepareactionmode(Android.view.ActionMode mode, menu menu) {return false;//Do not do anything returnfalse}@Override         Public Boolean onactionitemclicked(Android.view.ActionMode mode, MenuItem Item) {Switch(Item.getitemid ()) { CaseR.id.menu_edit:toast.maketext (mainactivity. This,"editing!", Toast.length_short). Show (); Mode.finish ();return true; CaseR.id.menu_delete://Trigger Delete actionMode.finish ();return true;default:return false; }    }//When the user exits the action module        @Override         Public void Ondestroyactionmode(Android.view.ActionMode mode) {Currentactionmode =NULL; }    };

Finally, bind to a view:

 Public  class mainactivity extends appcompatactivity {    //Tracking Contextual context    PrivateActionmode Currentactionmode;//TextView with context menu    PrivateTextView Tvname;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        Tvname = (TextView) Findviewbyid (r.id.tvname); Tvname.setonlongclicklistener (NewView.onlongclicklistener () {@Override             Public Boolean Onlongclick(View v) {if(Currentactionmode! =NULL) {return false;}                Startactionmode (Modelcallback); V.setselected (true);return true;    }        }); }
Apply to Adapterview

First we define an item item to apply the relevant module:

 Public  class mainactivity extends Activity {  //ListView and adapter  PrivateListView Lvitems;PrivateArraylist<string> Arrayitems;PrivateArrayadapter<string> Adapteritems;//Tracks current menu item  Private intCurrentlistitemindex;//Tracks Current Contextual action mode  PrivateActionmode Currentactionmode;@Override  protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);    Setcontentview (R.layout.activity_main); PopulateListView ();//Fill array with string items and attach to ListViewLvitems = (ListView) Findviewbyid (R.id.lvitems); Lvitems.setadapter (Adapteritems);//Setup Contextual action mode when item is clickedLvitems.setonitemlongclicklistener (NewAdapterview.onitemlongclicklistener () { Public Boolean Onitemlongclick(adapterview<?> parent, view view,intPositionLongID) {if(Currentactionmode! =NULL) {return;        } currentlistitemindex = position;        Currentactionmode = Startactionmode (Modecallback); View.setselected (true);return true;  }    }); }//... action mode definitions ....}

Now a long click will trigger the context module because we have stored it and currentListItemIndex then we can do the right thing for the selected item.

private ActionMode.Callback modeCallBack = new ActionMode.Callback() {  ...  // Called when the user selects a contextual menu item  @Override  public boolean onActionItemClicked(ActionMode mode, MenuItem item) {    switch (item.getItemId()) {    case R.id.menu_delete:      arrayItems.remove(currentListItemIndex); // 删除当前项      adapterItems.notifyDataSetChanged(); // Refresh adapter      mode.finish(); // Action picked, so close the contextual menu      return true;    default:      return false;    }  }  ...};

At some point we need to be able to influence more than one action, so we need to use MultiChoiceModelListener Https://developer.android.com/guide/topics/ui/menus.html#CABforListView

Popmenu

The

is a menu anchored to view that provides an overflow style menu for actions related to specific content. Remember that the context module is typically used for actions that affect content, and this menu is used for operations with content Magistrate, such as replying to information.
First, for example, we want to pop a menu with a button. We define an XML file of menu for a button menu/popup_filters.xml

<?xml version= "1.0" encoding= "Utf-8"?  <menu  xmlns: Android  = "http://schemas.android.com/apk/res/android" ;  <item  android:id  = "@+id/menu_keyword"  android:title  =" Keyword "/>  <item  android:id  = "@+id/menu_popularity"  android:title  =/>   </menu ;   

We then bind the listener to the button in the activity:

 @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main);//bindings-related listenersBtnfilter = (Button) Findviewbyid (r.id.btnfilter); Btnfilter.setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v)            {Showfilterpopup (v); }        });//Show menu on selected View    Private void Showfilterpopup(View v) {PopupMenu popup =NewPopupMenu ( This, v);//Load menu from XMLPopup.getmenuinflater (). Inflate (R.menu.popup_filters, Popup.getmenu ());//Create menu optionsPopup.setonmenuitemclicklistener (NewPopupmenu.onmenuitemclicklistener () {@Override             Public Boolean Onmenuitemclick(MenuItem Item) {Switch(Item.getitemid ()) { CaseR.id.menu_keyword:toast.maketext (mainactivity. This,"Keyword", Toast.length_short). Show ();return true; CaseR.id.menu_popularity:toast.maketext (mainactivity. This,"Popularity", Toast.length_short). Show ();return true;default:return false; }            }        });//Processing disappears: Popup.setondismisslistener (...)        //Display menuPopup.show (); }
Pop-up window

In addition to the above we have a more easily customizable Popwindow, he is a suspended content container appearing in the IQ of existing activities. Suitable for displaying additional information or information that the user wants to obtain after an event has occurred.
First we want to have a background image, as the background of the popup content, then we define a popup window layout filelayout/popup_content.xml

<relativelayout  xmlns: Android  = "http://schemas.android.com/apk/res/android"  android:layout_width  =" match_parent " android:layout_height  =" wrap_content " android:background  =" @drawable/popup_bg ";     <textview  android:id  = "@+id/tvcaption"  android:layout_width  = "wrap_content"  android:layout_height  = "wrap_content"  android:layout_ Centerhorizontal  = "true"  android:layout_ centervertical  = "true"  android:text  =<        Span class= "Hljs-value" > "This is a popup!"  android:textappearance  = "android:attr/ Textappearancelarge " android:textcolor  =" # FFFFFF "/> </relativelayout>

Then we need to define displayPopupWindow ways to build and showcase our windows, based on our content area and background images.

 Public  class demowindowactivity extends Activity { PrivateButton Btnshowpopup;@Override  protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_demo_window);//Locate the Show Popup button and attach click ListenerBtnshowpopup = (Button) Findviewbyid (r.id.btnshowpopup); Btnshowpopup.setonclicklistener (NewOnclicklistener () {@Override       Public void OnClick(View v) {//Display popup attached to the button as a position anchorDisplaypopupwindow (v);  }    }); }//Display popup attached to the button as a position anchor  Private void Displaypopupwindow(View Anchorview) {Popupwindow popup =NewPopupwindow (demowindowactivity. This); View layout = Getlayoutinflater (). Inflate (R.layout.popup_content,NULL); Popup.setcontentview (layout);//Set content width and heightPopup.setheight (WindowManager.LayoutParams.WRAP_CONTENT); Popup.setwidth (WindowManager.LayoutParams.WRAP_CONTENT);//Closes the popup window when touch outside of It-when looses focusPopup.setoutsidetouchable (true); Popup.setfocusable (true);//Show anchored to buttonPopup.setbackgrounddrawable (NewBitmapdrawable ());  Popup.showasdropdown (Anchorview); }}
Menu Group

In some cases we may want to combine menu options, and in the XML file we can simply use the group tags

<menu xmlns:android="Http://schemas.android.com/apk/res/android">    <item android:id="@+id/menu_save"android:icon="@drawable/ Menu_save "android:title=" @string/menu_save " />                        <!--menu Group --    <group android:id="@+id/group_delete">        <item android:id="@+id/menu_archive"android:title="@string/menu _archive " />                      <item android:id= "@+id/menu_delete"android:title="@ String/menu_delete " />                  </Group></Menu>
Library

Android-slideexpandablelistview:listview there's an area for each item that can be scratched.
Android-swipelistview:

Menus and popup windows

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.