Android中ContextMenu用法实例
本文实例讲述了Android中ContextMenu用法。分享给大家供大家参考。具体如下:
main.xml文件如下:
<?xmlversion="1.0"encoding="utf-8"?> <LinearLayoutxmlns:Android="http://schemas.android.com/apk/res/android" Android:orientation="vertical" Android:layout_width="fill_parent" Android:layout_height="fill_parent" > <ListView Android:id="@android:id/list" Android:layout_width="fill_parent" Android:layout_height="fill_parent"></ListView> </LinearLayout>
simple_list_item_1.xml文件如下:
<?xmlversion="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"> <TextView Android:id="@+id/label" Android:layout_width="fill_parent" Android:layout_height="wrap_content" Android:textSize="30sp"></TextView> </LinearLayout>
MenuDemoActivity.java如下:
packagecom.yyl; importAndroid.app.ListActivity; importAndroid.os.Bundle; importAndroid.view.ContextMenu; importAndroid.view.ContextMenu.ContextMenuInfo; importAndroid.view.Menu; importAndroid.view.MenuItem; importAndroid.view.View; importAndroid.widget.ArrayAdapter; publicclassMenuDemoActivityextendsListActivity{ publicstaticfinalintEIGHT_ID=Menu.FIRST+1; publicstaticfinalintSIXTEEN_ID=Menu.FIRST+2; publicstaticfinalintTWENTY_FOUR_ID=Menu.FIRST+3; publicstaticfinalintTWO_ID=Menu.FIRST+4; publicstaticfinalintTHIRTY_TWO_ID=Menu.FIRST+5; publicstaticfinalintFORTY_ID=Menu.FIRST+6; publicstaticfinalintONE_ID=Menu.FIRST+7; String[]items={"lorem","ipsum","dolor","sit","amet", "consectetuer","adipiscing","elit","morbi","vel", "ligula","vitae","arcu","aliquet","mollis", "etiam","vel","erat","placerat","ante", "porttitor","sodales","pellentesque","augue","purus"}; @Override publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); setListAdapter(newArrayAdapter(this,R.layout.simple_list_item_1,R.id.label,items)); //注册ContextView到view中 registerForContextMenu(getListView()); } //重写该方法,生成ContextMenu菜单 @Override publicvoidonCreateContextMenu(ContextMenumenu,Viewv, ContextMenuInfomenuInfo){ this.populateMenu(menu); super.onCreateContextMenu(menu,v,menuInfo); } privatevoidpopulateMenu(Menumenu){ menu.add(Menu.NONE,ONE_ID,Menu.NONE,"1Pixel"); menu.add(Menu.NONE,TWO_ID,Menu.NONE,"2Pixels"); menu.add(Menu.NONE,EIGHT_ID,Menu.NONE,"8Pixels"); menu.add(Menu.NONE,SIXTEEN_ID,Menu.NONE,"16Pixels"); menu.add(Menu.NONE,TWENTY_FOUR_ID,Menu.NONE,"24Pixels"); menu.add(Menu.NONE,THIRTY_TWO_ID,Menu.NONE,"32Pixels"); menu.add(Menu.NONE,FORTY_ID,Menu.NONE,"40Pixels"); } }
希望本文所述对大家的Android程序设计有所帮助。