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>

下面是Java代码:


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 Adapter;
	ArrayList arr=new ArrayList();
	//定义菜单项
	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(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); 
    	
    }

}

© 2010, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记