<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.dell.caidanxiang.contextmenu"
    android:orientation="vertical">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="长按触发上下文菜单"
        android:id="@+id/changan"/>

</LinearLayout>

 

JAVA文件

 

package com.example.dell.caidanxiang;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class contextmenu extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contextmenu);
        Button changan = (Button)findViewById(R.id.changan);

        changan.setOnCreateContextMenuListener(this);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {

        //编码模式,同OptionMenu一样
//        menu.add(1,1,0,"添加");
//        menu.add(1,2,1,"修改");
//        menu.add(1,3,2,"删除");

        MenuInflater me = getMenuInflater();

        me.inflate(R.menu.mymenu,menu);

        super.onCreateContextMenu(menu, v, menuInfo);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {

        Toast.makeText(contextmenu.this, "选项是"+item, Toast.LENGTH_SHORT).show();

        return super.onContextItemSelected(item);
    }
}

加载menu文件

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/it1"
        android:title="添加"
        ></item>

    <item android:id="@+id/it2"
        android:title="修改"
        ></item>

</menu>

 

posted on 2016-04-07 17:00  halooomo  阅读(521)  评论(0编辑  收藏  举报