发表于: 2018-12-26 19:20:05
0 797
今天完成的事情
ContextMenu
Extension of Menu for context menus providing functionality to modify the header of the context menu.Context menus do not support item shortcuts and item icons.
To show a context menu on long click, most clients will want to call Activity.registerForContextMenu(View) and override Activity.onCreateContextMenu(ContextMenu, View, ContextMenu.ContextMenuInfo).
当一个View注册了ContextMenu,长按该View就会弹出ContextMenu,ContextMenu继承自View.Menu,所以可以像OptionMenu那样添加菜单选项。
基本的使用方法:
1、注册
registerForContextMenu(view);
2.创建菜单
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
menu.add(1, 0, 1, "删除会话");
menu.add(1, 1, 1, "删除所有会话");
}
3、菜单选中事件
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
//......
break;
case 1:
//......
break;
}
return super.onContextItemSelected(item);
}
看上去很简单,但ContextMenu多数出现的场景是在RecyclerView中,比如长按RecyclerView中的item弹出复制、粘贴、移动、删除等选项,而上面的方法并不适用于RecyclerView。
在RecyclerView中实现ContextMenu:
主要思路:Adapter中,在onCreateView()方法中为子项view设置OnCreateContextMenuListener和OnLongClickListener,设置OnLongClickListener的目的是为了获取子项view对应的option,以便获取相应的填充对象。
另外需要注意onLongClick()方法的返回值,如果只注册了OnLongClickListener这一个点击事件,那么这个值不会起作用,但当同一个View注册了多个点击事件时,当返回值为false时,执行完longClick事件后还会继续去执行其他点击事件,设为true则不会。
这里设为false,longClick事件中获取到option后继续执行onCreateContextMenu,这样就能将option传递下去,方便之后的操作。
@Override
@NonNull
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_conversation, parent, false);
//设置item长按事件
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
if (onItemLongClickListener != null) {
onItemLongClickListener.onItemLongClick((Integer) view.getTag());
}
return false;
}
});
//设置OnCreateContextMenuListener
view.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.add(1, 0, 1, "删除会话");
menu.add(1, 1, 1, "删除所有会话");
}
});
return new ConversationViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
ConversationViewHolder conversationViewHolder = (ConversationViewHolder) holder;
conversationViewHolder.bindData(context, conversationList.get(position));
conversationViewHolder.itemView.setTag(position);
}
在Activity或Fragment中:
@Override
public void onItemLongClick(int position) {
clickOption = position;
Log.i(TAG, "onItemLongClick: position= " + clickOption);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0
Conversation conversation = conversationAdapter.getConversation(clickOption);
//......
break;
case 1:
//......
break;
default:
break;
}
return super.onContextItemSelected(item);
}
明天的计划
日志、断点调试
遇到的问题
收获
ContextMenu
LongClick
评论