ListView结合ContextMenu 获取点击项的Position

阅读更多

ContextMenu称为上下文菜单,一般在控件上长按时弹出。今天我们学习ContextMenu的用法,这里与listview相结合,先在ListView显示几个Item,然后在Item上长按,弹出一个菜单(就是ContextMenu),点击菜单上的项目,提示刚才长按的Item的Position.

main.xml 里就一个ListView

 





 

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); 
 
    }
 
}

 

 

List 中显示context Menu

// get the list view
ListView list = (ListView)findViewById(R.id.list);
// set adapter before registering the context menu
list.setAdapter(adapter);
// register it for the context menu
registerForContextMenu(list);

你可能感兴趣的:(ListView结合ContextMenu 获取点击项的Position)