原文:http://www.cnblogs.com/JinyaoLi/p/3868719.html
实现自己的Contextual Action Mode
一种4.0后新的显示menu的方式,将Menu显示在ActionBar上。
如果TextView设置了(API11)
android:textIsSelectable="true"
那么在你长按TextView就会显示
我们可以自己实现这个ActionMode,并自定义它的样式。
为一个独立的View实现contextual action mode,有两步:
1.实现ActionMode.Callback接口。
2.当你想要显示ActionMode时,运行startActionMode()(or getActivity().startActionMode() for a fragment)
1.实现ActionMode.Callback接口。
1 //用来标记ActionMode和做出相关设置 2 private ActionMode mActionMode; 3 private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() { 4 // Called each time the action mode is shown. Always called after onCreateActionMode, but 5 // may be called multiple times if the mode is invalidated. 6 @Override 7 public boolean onPrepareActionMode(ActionMode arg0, Menu arg1) { 8 // TODO Auto-generated method stub 9 return false; 10 } 11 // Called when the user exits the action mode 12 @Override 13 public void onDestroyActionMode(ActionMode arg0) { 14 // TODO Auto-generated method stub 15 Toast.makeText(getApplicationContext(), "Action Mode Closed",Toast.LENGTH_SHORT).show(); 16 mActionMode = null; 17 } 18 // Called when the action mode is created; startActionMode() was called 19 @Override 20 public boolean onCreateActionMode(ActionMode mode, Menu menu) { 21 // TODO Auto-generated method stub 22 MenuInflater inflater = mode.getMenuInflater(); 23 inflater.inflate(R.menu.main_context_menu, menu); 24 return true; 25 } 26 // Called when the user selects a contextual menu item 27 @Override 28 public boolean onActionItemClicked(ActionMode arg0, MenuItem arg1) { 29 // TODO Auto-generated method stub 30 int id = arg1.getItemId(); 31 32 return false; 33 } 34 };
2.运行startActionMode()
1 mActionMode = startSupportActionMode(mActionModeCallback); 2 mActionMode.setTitle("contextual action mode");
运行startActionMode()之后会得到一个ActionMode对象,可以通过这个对象来实现设置标题,finish 当前的ActionMode等操作。
接下来,我们可以自定义ActionMode的样式,包括删除CloseButton旁边的Divider。
1 <style name="MyActionBarTheme" parent="@style/Theme.AppCompat.Light"> 2 <item name="android:actionBarStyle">@style/MyActionBar</item> 3 <item name="android:actionModeCloseDrawable">@drawable/ic_launcher</item> 4 <item name="android:actionModeBackground">@color/yellow</item> 5 6 <!-- ActionMode右边的按钮是一个特殊的CloseButton,分割线与CloseButton的Style有关 --> 7 <!-- 删除ActionMode的Divider--> 8 <item name="android:actionModeCloseButtonStyle">@null</item> 9 </style> 10 11 <style name="MyActionBar" parent="@style/Widget.AppCompat.ActionBar"> 12 <item name="android:background">@color/green</item> 13 </style>
效果:
可兼容2.1(虽然虚拟机是2.3;没有定义标题文字颜色,由于父主题的原因标题文字白色,可以定义成黑色)