Context Menu Android Tutorial
Join the DZone community and get the full member experience.
Join For FreeGoing straight to the example, first I create a ListView with names of pens displayed. When one presses and holds one of the names for a long time, the context menu appears as shown here:
public class ShowContextMenu extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.names)));
…
}
Note that instead of hard-coding the list items as string array within the class, I have followed the best practice of externalizing the strings into a strings.xml resource class. Hence I use getResources().getStringArray(R.array.names) to retrieve the array of pen names that I want to display in the List. The strings.xml file in the value folder has this entry:
<string-array name="names">
<item>MONT Blanc</item>
<item>Gucci</item>
<item>Parker</item>
<item>Sailor</item>
<item>Porsche Design</item>
<item>Rotring</item>
<item>Sheaffer</item>
<item>Waterman</item>
</string-array>
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/edit"
android:title="@string/edit" />
<item android:id="@+id/save"
android:title="@string/save" />
<item android:id="@+id/delete"
android:title="@string/delete" />
<item android:id="@+id/view"
android:title="@string/view" />
</menu>
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
String[] names = getResources().getStringArray(R.array.names);
switch(item.getItemId()) {
case R.id.edit:
Toast.makeText(this, "You have chosen the " + getResources().getString(R.string.edit) +
" context menu option for " + names[(int)info.id],
Toast.LENGTH_SHORT).show();
return true;
…………………..
default:
return super.onContextItemSelected(item);
}
Published at DZone with permission of Sai Geetha M N, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
The SPACE Framework for Developer Productivity
-
A Complete Guide to AWS File Handling and How It Is Revolutionizing Cloud Storage
-
Observability Architecture: Financial Payments Introduction
-
RBAC With API Gateway and Open Policy Agent (OPA)
Comments