简洁大方,为自己的Android App添加一个ContextMenu

 

 

添加ContextMenu步骤:

if(Activity类)

1.声明一个ListView控件,并findViewById(id),或者GetListView()

2.在Activity的onCreate()中,为Activity设置OnCreateContextMenuListener

这时候,不需要写布局文件,就方便地拥有了一个呼出式的菜单

3.复写Activity的onContextItemSelected()

else if(ListActivity类)

1.在Activity的onCreate()中为List添加ContextMenu(重要一步)

registerForContextMenu(getListView());

 2.复写onCreateContextMenu方法与onContextItemSelected方法(注意不是设置监听器)


以下是已经被我折腾了的code

1.主程序.java

package jun.listviewContextMenu;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ListviewContextMenuActivity extends Activity
{
	// ===========================================================
	// Final Fields 静态变量
	// ===========================================================
	protected static final int CONTEXTMENU_DELETEITEM = 0;

	// ===========================================================
	// Fields 成员变量
	// ===========================================================

	// 用于获取ListView控件
	protected ListView mFavList;
	// 声明一个存放Favorite类型的LIST
	protected ArrayList<Favorite> fakeFavs = new ArrayList<Favorite>();

	// ===========================================================
	// "Constructors"
	// ===========================================================

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle icicle)
	{
		super.onCreate(icicle);
		setContentView(R.layout.main);

		/* Add some items to the list the listview will be showing. */
		fakeFavs.add(new Favorite("John", "nice guy"));
		fakeFavs.add(new Favorite("Yasmin", "hot girl"));
		fakeFavs.add(new Favorite("Jack", "cool guy"));

		this.mFavList = (ListView) this.findViewById(R.id.list_favorites);
		initListView();
	}

	private void refreshFavListItems()
	{
		mFavList.setAdapter(new ArrayAdapter<Favorite>(this,
				android.R.layout.simple_list_item_1, fakeFavs));
	}

	private void initListView()
	{
		/* Loads the items to the ListView. */
		refreshFavListItems();

		/*
		 * Add Context-Menu listener to the ListView.
		 * 为ListView设置监听器OnCreateContextMenuListener
		 */
		mFavList.setOnCreateContextMenuListener(new OnCreateContextMenuListener()
		{

			public void onCreateContextMenu(ContextMenu conMenu, View view,
					ContextMenuInfo info)
			{
				conMenu.setHeaderTitle("ContextMenu");
				// conMenu.add(0, 0, 0, "Delete this favorite!");
				//这里在设置常量的时候设置零有好的地方也有不好的地方
				//好处:	设置零会将这一项放在第一个
				//不好的地方: 当你不关心这些项目的顺序的时候,设置零就会导致其他按钮的出发这个按钮的事件
				//			  应为两个按钮的ITEM_ID是一样的
				conMenu.add(0, CONTEXTMENU_DELETEITEM, 0, "Delete this favorite!");
				conMenu.add(1, 0, 0, "Add More Information");
				conMenu.add(1, 0, 0, "Add New Person");
				conMenu.add(2, 0, 0, "Update 1");
				conMenu.add(1, 0, 0, "3rd Item");
				conMenu.add(2, 0, 0, "Update 2");
				
				//PS:groupid相同的ContextMenu不会放在一起,而是根据他们添加的顺序

				/* Add as many context-menu-options as you want to. */
			}
		});

		mFavList.setOnItemClickListener(new OnItemClickListener()
		{

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3)
			{
				// TODO Auto-generated method stub
				Toast.makeText(ListviewContextMenuActivity.this,
						"111111111111", 200).show();
			}

		});
	}

	// ===========================================================
	// Methods from SuperClass/Interfaces
	// ===========================================================

	@Override
	public boolean onContextItemSelected(MenuItem aItem)
	{
		ContextMenuInfo menuInfo = (ContextMenuInfo) aItem.getMenuInfo();

		/*
		 * Switch on the ID of the item, to get what the user selected.
		 * 在前面设置itemID常量,来检测选中了哪一项
		 */
		switch (aItem.getItemId())
		{
		case CONTEXTMENU_DELETEITEM:
			/* Get the selected item out of the Adapter by its position. */
			Favorite favContexted = (Favorite) mFavList.getAdapter().getItem(0);
			/* Remove it from the list. */
			fakeFavs.remove(favContexted);

			refreshFavListItems();
			return true; /* true means: "we handled the event". */
		}
		return false;
	}

	// ===========================================================
	// Inner and Anonymous Classes 匿名内部类
	// ===========================================================

	/** Small class holding some basic */
	protected class Favorite
	{

		protected String name;
		protected String kindness;

		/**
		 * 简单的构造函数
		 * 
		 * @param name
		 * @param kindness
		 */
		protected Favorite(String name, String kindness)
		{
			this.name = name;
			this.kindness = kindness;
		}

		/** The ListView is going to display the toString() return-value! */
		// toString函数
		public String toString()
		{
			return name + " (" + kindness + ")";
		}

		public boolean equals(Object o)
		{
			// o是Faorite类的实例 && 传入的这个o的name与左边调用这个equal方法的实例的name一样(字符一样,顺序一样)
			return o instanceof Favorite
					&& ((Favorite) o).name.compareTo(name) == 0;
		}
	}
}

 2.布局文件 main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android ="http://schemas.android.com/apk/res/android"    
     android:orientation ="vertical"    
     android:layout_width ="fill_parent"    
     android:layout_height ="fill_parent" >    
     <TextView    
          android:layout_width ="fill_parent"    
          android:layout_height ="wrap_content"    
          android:text ="Long-Press on of the Items in the list." />    
     <ListView android:id ="@+id/list_favorites"    
          android:layout_width ="fill_parent"    
          android:layout_height ="fill_parent" />    
</LinearLayout>  
原文地址:https://www.cnblogs.com/jun14/p/2459806.html