【Android】菜单功能的实现:上下文菜单


1.在主面板里面添加一个列表视图,如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >
    </ListView>

</RelativeLayout>

2.要实现的功能就是在List上长按,然后弹出菜单,菜单代码布局如下:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/edit"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="Edit"/>
    <item
        android:id="@+id/share"
        android:orderInCategory="101"
        android:showAsAction="never"
        android:title="Share"/>
    <item
        android:id="@+id/delete"
        android:orderInCategory="102"
        android:showAsAction="never"
        android:title="Delete"/>

</menu>

3.为ListView注册上下文菜单:

@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	listView = (ListView) this.findViewById(R.id.listView1);
	ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
			android.R.layout.simple_list_item_1, getData());
	listView.setAdapter(adapter);
	// 给listView注册上下文菜单
	registerForContextMenu(listView);
}

public List<String> getData() {
	List<String> list = new ArrayList<String>();
	for (int i = 1; i <= 7; i++) {
		list.add("jack" + i);
	}
	return list;
}

4.此时可以看到列表,但还无法弹出菜单。加载菜单代码如下:

// 上下文菜单
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub

		// 加载XML中的上下文菜单
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main, menu);
	}

此时可以弹出菜单。

5.定义选项的动作。

// 相应上下文菜单的操作
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.delete:
			Toast.makeText(this, "delete", Toast.LENGTH_SHORT).show();
			break;
		case R.id.share:
			Toast.makeText(this, "share", Toast.LENGTH_SHORT).show();
			break;
		case R.id.edit:
			Toast.makeText(this, "edit", Toast.LENGTH_SHORT).show();
			break;
		default:
			break;
		}

		return super.onContextItemSelected(item);
	}



你可能感兴趣的:(android)