Android 上下文菜单 ActionMode

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

长按显示菜单

image

选择菜单

image

posted @ 2019-11-04 15:49  thomas_blog  阅读(885)  评论(0编辑  收藏  举报