77import android .os .Bundle ;
88import android .preference .PreferenceManager ;
99import android .util .Log ;
10+ import android .view .ActionMode ;
1011import android .view .Menu ;
1112import android .view .MenuInflater ;
1213import android .view .MenuItem ;
1819public class OverviewActivity extends Activity {
1920 private static final String TAG = "de.vogella.android.socialapp" ;
2021 SharedPreferences preferences ;
22+ protected Object mActionMode ;
2123
2224 @ Override
2325 public void onCreate (Bundle savedInstanceState ) {
@@ -43,6 +45,23 @@ public void onClick(View v) {
4345 updatePreferenceValue ();
4446 }
4547 });
48+ // Define the contextual action mode
49+ View view = findViewById (R .id .myView );
50+ view .setOnLongClickListener (new View .OnLongClickListener () {
51+ // Called when the user long-clicks on someView
52+ public boolean onLongClick (View view ) {
53+ if (mActionMode != null ) {
54+ return false ;
55+ }
56+
57+ // Start the CAB using the ActionMode.Callback defined above
58+ mActionMode = OverviewActivity .this
59+ .startActionMode (mActionModeCallback );
60+ view .setSelected (true );
61+ return true ;
62+ }
63+ });
64+
4665 }
4766
4867 private void showPrefs (String username , String password ) {
@@ -106,4 +125,42 @@ public boolean onOptionsItemSelected(MenuItem item) {
106125 }
107126 return true ;
108127 }
128+
129+ private ActionMode .Callback mActionModeCallback = new ActionMode .Callback () {
130+
131+ // Called when the action mode is created; startActionMode() was called
132+ public boolean onCreateActionMode (ActionMode mode , Menu menu ) {
133+ // Inflate a menu resource providing context menu items
134+ MenuInflater inflater = mode .getMenuInflater ();
135+ // Assumes that you have "contexual.xml" menu resources
136+ inflater .inflate (R .menu .contextual , menu );
137+ return true ;
138+ }
139+
140+ // Called each time the action mode is shown. Always called after
141+ // onCreateActionMode, but
142+ // may be called multiple times if the mode is invalidated.
143+ public boolean onPrepareActionMode (ActionMode mode , Menu menu ) {
144+ return false ; // Return false if nothing is done
145+ }
146+
147+ // Called when the user selects a contextual menu item
148+ public boolean onActionItemClicked (ActionMode mode , MenuItem item ) {
149+ switch (item .getItemId ()) {
150+ case R .id .toast :
151+ Toast .makeText (OverviewActivity .this , "Selected menu" ,
152+ Toast .LENGTH_LONG ).show ();
153+ mode .finish (); // Action picked, so close the
154+ return true ;
155+ default :
156+ return false ;
157+ }
158+ }
159+
160+ // Called when the user exits the action mode
161+ public void onDestroyActionMode (ActionMode mode ) {
162+ mActionMode = null ;
163+ }
164+ };
165+
109166}
0 commit comments