Here is source code of the Program to Demonstrate Contextual Mode in Android. The program is successfully compiled and run on a Windows system using Eclipse Ide. The program output is also shown below.
Main Activity
package com.example.contextual_action_mode; import android.app.Activity; import android.os.Bundle; import android.view.ActionMode; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Toast; public class MainActivity extends Activity { protected Object actiob; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); View view = findViewById(R.id.text); view.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View view) { if (actiob != null) { return false; } actiob = MainActivity.this.startActionMode(actiobCallback); view.setSelected(true); return true; } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { return true; } private ActionMode.Callback actiobCallback = new ActionMode.Callback() { public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.contextual, menu); return true; } public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case R.id.toast: Toast.makeText(MainActivity.this, "Selected menu", Toast.LENGTH_LONG).show(); mode.finish(); return true; default: return false; } } public void onDestroyActionMode(ActionMode mode) { actiob = null; } }; }
Activity_Main
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <EditText android:id="@+id ext" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" > <requestFocus /> </EditText> </LinearLayout>
advertisement
advertisement
Sanfoundry Global Education & Learning Series – 100+ Java Android Tutorials.
If you wish to look at all Tutorials, go to Java Android Tutorials.
If you find any mistake above, kindly email to [email protected]Related Posts:
- Practice Programming MCQs
- Apply for Computer Science Internship
- Apply for Java Internship
- Check Programming Books
- Practice Information Technology MCQs