ContextMenu菜单详解

呼延景同
2023-12-01
 * ListView三要素
 * 1:ListView组件
 * 2:适配器    ArrayAdapter(就显示一行文字) SimpleAdapter(图文并茂)  BaseAdapter(也有点击事件)
 * 3:数据集
 *  菜单分为三种
 *  1:上下文菜单  ContextMenu   一般都是结合组件使用  所以通一个方法注册即可registerForContextMenu(某个组件)
 *  2:选项菜单    OptionsMenu
 *  3:子菜单      SubMenu
 */
public class MainActivity extends Activity {
    private ListView mListView;
    private MyAdapter mAdapter;
    private ArrayList<String> mList = new ArrayList<>();
    private Context mContext = MainActivity.this;
    private final int DELETE_ITEM = 1;
    private final int TOAST_ITEM = 2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initData();
        initViews();
        mAdapter = new MyAdapter(mList,mContext);
        mListView.setAdapter(mAdapter);
        registerForContextMenu(mListView);
    }
    private void initViews(){
        mListView = (ListView) findViewById(R.id.ListView);
    }


    private void initData(){
        for(int i=0;i<10;i++){
            mList.add("你好"+i);
        }
    }
    //创建上下文菜单
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        //这是标题
        menu.add("这是上下文菜单");
        //参数1:小组的标记,参数2给他设置一个ID  参数3:怎么显示位置(0,1)
        menu.add(0,DELETE_ITEM,0,"删除");
        menu.add(0,TOAST_ITEM,0,"Toast用");


    }
    //这个就是给上下文菜单里面选项做点击事件
    @Override
    public boolean onContextItemSelected(MenuItem item) {


//        AdapterContextMenuInfo android考虑我们要操作适配器里的数据 所以提供一个类让他得到信息


        AdapterView.AdapterContextMenuInfo adapterContextMenuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();


        int position = adapterContextMenuInfo.position;
        //得到每个条目的ID
        int id = item.getItemId();
        switch (id){
            case DELETE_ITEM:
                mList.remove(position);
                mAdapter.notifyDataSetChanged();
                Toast.makeText(mContext,"这是删除选项",Toast.LENGTH_SHORT).show();
                break;
            case TOAST_ITEM:
                Toast.makeText(mContext, "这是Toast专用"+position, Toast.LENGTH_SHORT).show();
                break;
        }


        return super.onContextItemSelected(item);
    }
}
 类似资料: