欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android 上下文菜单 ContextMenu

程序员文章站 2022-11-06 20:05:17
public class MainActivity extends Activity { private ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(... ......
public class mainactivity extends activity {

    private listview listview;

    @override
    protected void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        setcontentview(r.layout.activity_main);

        listview = (listview) this.findviewbyid(r.id.listview);
        arrayadapter<string> adapter = new arrayadapter<string>(this, android.r.layout.simple_expandable_list_item_1,
                getdata());
        listview.setadapter(adapter);

        // 给listview注册上下文菜单
        registerforcontextmenu(listview);
    }

    public list<string> getdata() {
        list<string> list = new arraylist<string>();
        for (int i = 0; i < 7; i++) {
            list.add("thomas " + i);
        }

        return list;
    }

    @override
    public boolean oncreateoptionsmenu(menu menu) {
        // inflate the menu; this adds items to the action bar if it is present.
        getmenuinflater().inflate(r.menu.main, menu);
        return true;
    }

    @override
    public void oncreatecontextmenu(contextmenu menu, view v, contextmenuinfo menuinfo) {
        // todo auto-generated method stub
        super.oncreatecontextmenu(menu, v, menuinfo);

        menuinflater inflater = getmenuinflater();
        inflater.inflate(r.menu.main, menu);
    }

    // 上下文菜单被选择
    @override
    public boolean oncontextitemselected(menuitem item) {
        // todo auto-generated method stub
        switch (item.getitemid()) {
        case r.id.action_add:
            toast.maketext(this, "添加被点击", 1).show();
            break;
        case r.id.action_delete:
            toast.maketext(this, "删除被点击", 1).show();
            break;

        default:
            break;
        }

        return super.oncontextitemselected(item);
    }
}
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/action_add"
        android:orderincategory="100"
        android:showasaction="never"
        android:title="添加">
    </item>
    <item
        android:id="@+id/action_delete"
        android:orderincategory="100"
        android:showasaction="never"
        android:title="删除">
    </item>

</menu>

长按效果

选择菜单