Android 上下文菜单 ActionMode

三世轮回 提交于 2019-12-03 11:03:43
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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!