安卓在使用上下文菜单时遇到的问题

1、在使用contextMemu时最基本的实现就是长按listView的一个item然后弹出一个选项菜单,但是在contextMenu都配置完以后发现长按不会出现菜单。

问题:由于在listView适配器中设置了关于item的点击事件,覆盖掉了长按事件。

解决办法:将在adpter定义的onclick事件取消改为在main.activity中使用setOnItemClickListener来配置listView的点击方法。

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                System.out.println("你点击了第" + position + "个");
                //点击跳转
                Intent intent = new Intent(First_Page.this, SecondActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("text" , "newText");//为bundle绑定传输数据键值对
                intent.putExtras(bundle);//将bundle绑定在intent上
                startActivity(intent);
            }
        });
2、那么长按显示菜单解决了后怎么样实现对当前长按的item的操作呢?

首先这个操作应该定义在contextMenu的onContextItemSelected(MenuItem item)方法中。

    @Override
    public boolean onContextItemSelected(MenuItem item){
        AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        int position = menuInfo.position;//获取当前活跃选项的id
        switch(item.getItemId()){
            ....
        }
        return super.onContextItemSelected(item);
    }

然后就是最关键的一步,首先要理解从哪里获取到要操作的listView的item的索引:

//这个方法用来获取当前活跃的item的信息对象
AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
//对象中有关于item的信息,我们需要position属性。
int position = menuInfo.position;
> 因为我实现删除操作是遇到了一个小问题所以这特意讲一下增删item的情况:

如果需要增加或删除这个item我们需要将之前适配adapt所用的存储数据的arryaList(我自定义为myBean)中的数据用remove()方法移除掉,但是这样会报错:

The content of the adapter has changed but ListView did not receive a notification.

这是因为arrayList中的数据和adapter不是热更新(因为觉得像web中的热更新模式)的,所以数据变了但是adapter没有接收到,所以我们需要通知adapter数据变了:

//首先获取adapter对象
  myAdapter adapter = (myAdapter)listView.getAdapter();
//调用通知方法
  adapter.notifyDataSetChanged();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值