ContextMenu Advanced Usage

Source: Internet
Author: User

51CT0 does not support markdown, please refer to the original: Pinterest

Keyword: ContextMenu

# #背景

We often in the list of pages, click on the list of rows, generally go to the details page, long press the list of a row, will pop up a menu, contains the action on a row (edit, delete, etc.), but also know the usual usage:

-0x01. Registering a view in activity that requires a context menu:

' Registerforcontextmenu (mlistview); '

-0x02. Then inherit the Oncreatecontextmenu method in the activity and add the menu item:

```

@Override

public void Oncreatecontextmenu (ContextMenu menu, View V, contextmenu.contextmenuinfo menuinfo) {

LOG.D (Log_tag, "Oncreatecontextmenu");

Super.oncreatecontextmenu (menu, V, menuinfo);

Menu.setheadertitle (r.string.prompt);

Menu.add (Menu.none, R.id.context_menu_item_delete_record, Menu.none, R.string.delete_record);//groupId, ItemId, Order, Title

Menu.add (Menu.none, R.id.context_menu_item_delete_record_with_file, Menu.none, r.string.delete_record_with_file);

}```

**ps: This method will be called every time the context menu appears * *

```

/** * Called when a context menu for the {@code view} are about

be shown. * Unlike {@link #onCreateOptionsMenu (Menu)}, this would

be called every * time the context menu was about to be shown and

Should is populated for * The view (or item inside the view for {@link

Adapterview} subclasses, * This can is found in the {@code

Menuinfo})). * <p> * Use {@link #onContextItemSelected (Android.view.MenuItem)} to know if an

* Item has been selected. * <p> * It isn't safe to hold onto the

Context menu After this method returns. * */

public void Oncreatecontextmenu (ContextMenu menu, View V, contextmenuinfo menuinfo) {

}

```

-0x03. The context menu pops up when you press and hold a row in the list:

! [Device-2015-11-04-141103.png] (http://upload-images.jianshu.io/upload_images/728306-c1f997a517d009c7.png?imageMogr2/auto-orient/strip% 7cimageview2/2/w/1240)

-0x04. After clicking on the menu, inherit the Oncontextitemselected method in the activity to process it:

```

@Override

public boolean oncontextitemselected (MenuItem item) {

Switch (Item.getitemid ()) {

}

}

```

-0x05. Get item ID (ID)

When we delete a database or a row of records, we need to know the primary key (usually ID) to operate, a lot of people think of ways, some of the ListView each Itemview add a longclicklistener, and then long press the time to record position, It is then processed accordingly.

In fact there is a more elegant approach, oncontextitemselected (MenuItem Item) callback parameter item can get Item.getmenuinfo (), in ListView and Adapter mode, Can be forced to convert to Adaptercontextmenuinfo, get TargetView (that is, the director of the line itemvew, if we need any parameters, directly into the View.settag can be):

```

Adaptercontextmenuinfo info = (adaptercontextmenuinfo) item.getmenuinfo ();

int index = info.position;

View view = Info.targetview;

```

At this point, the common usage is over, so you encounter other custom view?

-0x06. ContextMenu implementation of Custom view

In the example below, we need to handle the ContextMenu without the Recycleview of the ListView and its adapter.

The most important is the two ways to inherit view:

1. Additional information about the context menu item (above Item.getmenuinfo ());

```

/** * Views should implement this if they has extra information to

Associate * With the context menu. The return result is supplied as a

parameter to * the {@link

Oncreatecontextmenulistener#oncreatecontextmenu (ContextMenu,

View, Contextmenuinfo)} * callback. * * @return Extra information

About the item for which the context menu * should is shown.

This information would vary across different * subclasses of View. */

Protected Contextmenuinfo Getcontextmenuinfo () {

return null;

}

```

2.ViewGroup Showcontextmenuforchild, each popup context menu will call this method, need to update contextmenuinfo here;

```

/** * {@inheritDoc} */

public boolean showcontextmenuforchild (View originalview) {

return mparent! = null && mparent.showcontextmenuforchild (Originalview);

}

```

-0x07. ContextMenu all code for custom Recycleview


```

Package Com.lbrant.phone.view;


Import Android.content.Context;

Import Android.support.v7.widget.RecyclerView;

Import Android.util.AttributeSet;

Import Android.util.Log;

Import Android.view.ContextMenu;

Import Android.view.View;


/**

* Dell

* Time: 2015/11/3-18:34

* File: Phonerecorder

Description

*/

public class Contextmenurecyclerview extends Recyclerview {

private static final String Log_tag = "Contextmenurecyclerview";

Private Recyclercontextmenuinfo Mcontextmenuinfo = new Recyclercontextmenuinfo ();


Public Contextmenurecyclerview (Context context) {

Super (context);

}


Public Contextmenurecyclerview (context context, AttributeSet Attrs) {

Super (context, attrs);

}


Public Contextmenurecyclerview (context context, AttributeSet attrs, int defstyle) {

Super (context, attrs, Defstyle);

}


@Override

Protected Contextmenu.contextmenuinfo Getcontextmenuinfo () {

return mcontextmenuinfo;

}


@Override

public boolean showcontextmenuforchild (View originalview) {

LOG.D (Log_tag, "showcontextmenuforchild");

Object tag = Originalview.gettag ();

if (tag instanceof Recycleritemmarker) {

Mcontextmenuinfo.mrecycleitemmarker = (recycleritemmarker) tag;

}


Return Super.showcontextmenuforchild (Originalview);

}


public static class Recycleritemmarker {

public final int position;

public final Object obj;


public Recycleritemmarker (int position, Object obj) {

This.position = position;

This.obj = obj;

}

}


public static class Recyclercontextmenuinfo implements Contextmenu.contextmenuinfo {

Public Recycleritemmarker Mrecycleitemmarker;

}

}


Private class Recordrecycleviewadapter extends Recyclerview.adapter<recordrecycleviewadapter.recordviewholder > {

Private Cursor mcallrecordcursor;

private int midindex;

private int mphonenumberindex;

private int mcalltimeindex;

private int mdurationindex;

private int mpathindex;


Public recordrecycleviewadapter (cursor cursor) {

Mcallrecordcursor = cursor;

Updatecursorcolumnindex ();

}


private void Updatecursorcolumnindex () {

if (mcallrecordcursor! = null) {

Midindex = Mcallrecordcursor.getcolumnindex (basedatabasehelper.records_columns._id);

Mphonenumberindex = Mcallrecordcursor.getcolumnindex (basedatabasehelper.records_columns. number);

Mcalltimeindex = Mcallrecordcursor.getcolumnindex (basedatabasehelper.records_columns. Call_time);

Mdurationindex = Mcallrecordcursor.getcolumnindex (basedatabasehelper.records_columns. DURATION);

Mpathindex = Mcallrecordcursor.getcolumnindex (basedatabasehelper.records_columns. PATH);

}

}


@Override

Public Recordrecycleviewadapter.recordviewholder Oncreateviewholder (viewgroup parent, int viewtype) {

View Contentview = Layoutinflater.from (Parent.getcontext ()). Inflate (R.layout.record_list_item, parent, false);

Recordviewholder Viewholder = new Recordviewholder (Contentview);

return viewholder;

}


@Override

public void Onbindviewholder (Recordrecycleviewadapter.recordviewholder holder, final int position) {

Holder.itemView.setLongClickable (TRUE);

if (mcallrecordcursor! = null && mcallrecordcursor.movetoposition (position)) {

Long id = mcallrecordcursor.getlong (midindex);

String PhoneNumber = mcallrecordcursor.getstring (Mphonenumberindex);

Long seconds = Mcallrecordcursor.getlong (Mdurationindex);

String calltime = mcallrecordcursor.getstring (Mcalltimeindex);

String path = mcallrecordcursor.getstring (Mpathindex);

String Duration = String.Format ("%1$02d:%2$02d:%3$02d", seconds/3600, seconds% 3600/60, seconds% 60);


RecordInfo info = new RecordInfo ();

Info.setid (ID);

Info.setphonenumber (PhoneNumber);

Info.setsecondsduration (seconds);

Info.setcalltime (Calltime);

Info.setpath (path);


Holder.itemView.setTag (new Contextmenurecyclerview.recycleritemmarker (position, info));

Holder.mTextViewPhoneNumber.setText (PhoneNumber);

Holder.mTextViewDuration.setText (duration);

Holder.mTextviewCallTime.setText (Calltime);


cursor cursor = Querycontactbyphonenumber (ContactsContract.CommonDataKinds.Phone.NUMBER + "= '" + PhoneNumber + "'");

if (cursor! = NULL) {

if (Cursor.movetonext ()) {

Long contactId = cursor.getint (0);

Cursor contactcursor = querycontact (contactscontract.contacts._id + "=" + contactId);

if (contactcursor! = null) {

Holder.mTextViewName.setText (contactcursor.getstring (1));

Contactcursor.close ();

}

}

Cursor.close ();

}

}

}


@Override

public void onviewrecycled (Recordviewholder holder) {

super.onviewrecycled (holder);

Holder.itemView.setOnCreateContextMenuListener (NULL);

}


@Override

public int GetItemCount () {

return mcallrecordcursor = = null? 0:mcallrecordcursor.getcount ();

}


public void Changecursor (cursor cursor) {

if (cursor! = mcallrecordcursor) {

if (mcallrecordcursor! = null) {

Mcallrecordcursor.close ();

}

Mcallrecordcursor = cursor;

Updatecursorcolumnindex ();

Notifydatasetchanged ();

}

}


public class Recordviewholder extends Recyclerview.viewholder {

Private ImageView Mimageviewavatar;

Private TextView Mtextviewphonenumber;

Private TextView Mtextviewname;

Private TextView Mtextviewcalltime;

Private TextView mtextviewduration;


Public Recordviewholder (View Itemview) {

Super (Itemview);

Mimageviewavatar = (ImageView) Itemview.findviewbyid (R.id.imageviewavatar);

Mtextviewname = (TextView) Itemview.findviewbyid (r.id.textviewname);

Mtextviewphonenumber = (TextView) Itemview.findviewbyid (R.id.textviewphonenumber);

Mtextviewcalltime = (TextView) Itemview.findviewbyid (r.id.textviewcalltime);

Mtextviewduration = (TextView) Itemview.findviewbyid (r.id.textviewduration);

}

}

}

```

* * There are two places to be aware of: * *

Add tag to Itemview in 1.onBindViewHolder;

2. Set Itemview's longclickable to true, otherwise the context menu will not appear (for specific reasons see ContextMenu principle analysis);

Holder.itemView.setLongClickable (TRUE);


This article is from the "Beyond the Dream" blog, please be sure to keep this source http://lbrant.blog.51cto.com/2400264/1709643

ContextMenu Advanced Usage

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.