ListView结合ContextMenu 获取点击项的Position
ContextMenu称为上下文菜单,一般在控件上长按时弹出。今天我们学习ContextMenu的用法,这里与listview相结合,先在ListView显示几个Item,然后在Item上长按,弹出一个菜单(就是ContextMenu),点击菜单上的项目,提示刚才长按的Item的Position.
main.xml 里就一个ListView
<?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" > <ListView android:id="@+id/lv" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout>
package com.pocketdigi.com; import java.util.ArrayList; import android.app.Activity; import android.os.Bundle; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class main extends Activity { /** Called when the activity is first created. */ ListView lv; ArrayAdapter<String> Adapter; ArrayList<String> arr=new ArrayList<String>(); //定义菜单项 protected static final int Menu_Item1=Menu.FIRST; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); lv=(ListView)findViewById(R.id.lv); //添加ListView项 arr.add("123"); arr.add("234"); arr.add("345"); Adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, arr); lv.setAdapter(Adapter); lv.setOnCreateContextMenuListener(MenuLis); } ListView.OnCreateContextMenuListener MenuLis=new ListView.OnCreateContextMenuListener(){ @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { // TODO Auto-generated method stub //添加菜单项 menu.add(Menu.NONE,Menu_Item1,0,"获取position"); } }; //选中菜单Item后触发 public boolean onContextItemSelected(MenuItem item){ //关键代码在这里 AdapterView.AdapterContextMenuInfo menuInfo; menuInfo =(AdapterView.AdapterContextMenuInfo)item.getMenuInfo(); //输出position Toast.makeText(main.this,String.valueOf(menuInfo.position), Toast.LENGTH_LONG).show(); return super.onContextItemSelected(item); } }
List 中显示context Menu
// get the list view
ListViewlist=(ListView)findViewById(R.id.list);
//setadapterbeforeregisteringthecontextmenu
list.setAdapter(adapter);
//registeritforthecontextmenu
registerForContextMenu(list);
相关推荐
magic00 2019-10-21
chenjinlong 2020-02-19
83580494 2013-07-19
langjiao 2013-07-16
kiduo0 2013-07-10
gongzhiyao0 2010-11-15
bigdatazx 2010-11-05
Urchindong 2011-08-01
peixiaopao 2011-08-21
MeOrdinary 2014-05-13
guizhongyun 2011-09-27
csuhanshuai 2015-03-30
Sunanang 2015-03-30
snailbing 2015-04-23
huohu00 2015-04-22
toperfect 2015-07-01
nickey 2012-01-29
Rgenxiao 2012-01-26
满城风絮 2011-12-03