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

本文介绍如何在Android应用中实现上下文菜单功能,包括在Activity和ListActivity中添加上下文菜单的方法,以及如何通过代码注册监听器并处理菜单项点击事件。

 

 

添加ContextMenu步骤:

if(Activity类)

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

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

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

3.复写Activity的onContextItemSelected()

else if(ListActivity类)

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

?
1
registerForContextMenu(getListView());

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


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

1.主程序.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
<?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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值