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

Android 上下文菜单 ActionMode

程序员文章站 2022-05-09 12:00:43
public class MainActivity extends Activity { private Button button; private ActionMode actionMode; @Override protected void onCreate(Bundle savedInsta... ......
public class mainactivity extends activity {

    private button button;
    private actionmode actionmode;

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

        button = (button) findviewbyid(r.id.button);

        button.setonlongclicklistener(new onlongclicklistener() {

            @override
            public boolean onlongclick(view v) {
                // todo auto-generated method stub
                if (actionmode != null) {
                    return false;
                } else {
                    actionmode = startactionmode(actioncallback);
                    v.setselected(true);
                    return true;
                }
            }
        });
    }

    private actionmode.callback actioncallback = new actionmode.callback() {

        @override
        public boolean onprepareactionmode(actionmode mode, menu menu) {
            // todo auto-generated method stub
            return false;
        }

        @override
        public void ondestroyactionmode(actionmode mode) {
            // todo auto-generated method stub

        }

        // 从xml菜单中加载菜单
        @override
        public boolean oncreateactionmode(actionmode mode, menu menu) {
            // todo auto-generated method stub

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

            return true;
        }

        // 菜单被点击
        @override
        public boolean onactionitemclicked(actionmode mode, menuitem item) {
            // todo auto-generated method stub

            switch (item.getitemid()) {
            case r.id.action_add:
                toast.maketext(mainactivity.this, "添加被点击", 1).show();
                break;

            case r.id.action_delete:
                toast.maketext(mainactivity.this, "删除被点击", 1).show();
                break;
            default:
                break;
            }

            return false;
        }
    };
}

长按显示菜单

选择菜单