Login     Sign Up
Tugadar (@admin)
21 days ago
25 Views

In the following example, you’ll be adding some simple menu functions to the To-Do List application you started in Chapter 2 and continued to improve previously in this chapter.

You will add the ability to remove items from Context and Activity Menus, and improve the use of screen space by displaying the text entry box only when adding a new item.

Start by importing the packages you need to support menu functionality into the ToDoList Activity class.

import android.view.Menu;

import android.view.MenuItem;

import android.view.ContextMenu;

import android.widget.AdapterView;

Then add private static final variables that define the unique IDs for each Menu Item.

static final private int ADD_NEW_TODO = Menu.FIRST; static final private int REMOVE_TODO = Menu.FIRST + 1;

Now override the onCreateOptionsMenu method to add two new Menu Items, one to add and the other to remove the to-do item. Specify the appropriate text, and assign icon resources and shortcut keys for each item.

@Override

public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu);

// Create and add new menu items.

MenuItem itemAdd = menu.add(0, ADD_NEW_TODO, Menu.NONE, R.string.add_new);

MenuItem itemRem = menu.add(0, REMOVE_TODO, Menu.NONE, R.string.remove);

Assign icons itemAdd.setIcon(R.drawable.add_new_item); itemRem.setIcon(R.drawable.remove_item);

Allocate shortcuts to each of them.

itemAdd.setShortcut(‘0’, ‘a’);

itemRem.setShortcut(‘1’, ‘r’);

return true;

}

If you run the Activity, pressing the Menu button should appear as shown in Figure 4-7.

Having populated the Activity Menu, create a Context Menu. First, modify onCreate to regis-ter the ListView to receive a Context Menu. Then override onCreateContextMenu to populate the menu with a “remove” item.

@Override

public void onCreate(Bundle icicle) {

... existing onCreate method ... ] registerForContextMenu(myListView);

}

@Override

public void onCreateContextMenu(ContextMenu menu,

View v,

ContextMenu.ContextMenuInfo menuInfo) {

super.onCreateContextMenu(menu, v, menuInfo);

menu.setHeaderTitle(“Selected To Do Item”); menu.add(0, REMOVE_TODO, Menu.NONE, R.string.remove);

}

Now modify the appearance of the menu based on the application context, by overriding the onPrepareOptionsMenu method. The menu should be customized to show “cancel” rather than “delete” if you are currently adding a new Menu Item.

private boolean addingNew = false;

@Override

public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu);

int idx = myListView.getSelectedItemPosition();

String removeTitle = getString(addingNew ?

R.string.cancel : R.string.remove);

MenuItem removeItem = menu.findItem(REMOVE_TODO); removeItem.setTitle(removeTitle); removeItem.setVisible(addingNew || idx > -1);

return true;

}

For the code in Step 5 to work, you need to increase the scope of the todoListItems and ListView control beyond the onCreate method. Do the same thing for the ArrayAdapter and EditText to support the add and remove actions when they’re implemented later.

private ArrayList<String> todoItems;

private ListView myListView;

private EditText myEditText;

private ArrayAdapter<String> aa;

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

Inflate your view setContentView(R.layout.main);

Get references to UI widgets

myListView = (ListView)findViewById(R.id.myListView); myEditText = (EditText)findViewById(R.id.myEditText);

todoItems = new ArrayList<String>();

int resID = R.layout.todolist_item;

= new ArrayAdapter<String>(this, resID, todoItems); myListView.setAdapter(aa);

myEditText.setOnKeyListener(new OnKeyListener() {

public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN)

if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)

{

todoItems.add(0, myEditText.getText().toString()); myEditText.setText(“”);
aa.notifyDataSetChanged();

return true;

}

return false;

}

});

registerForContextMenu(myListView);

}

Next you need to handle Menu Item clicks. Override the onOptionsItemSelected and onContextItemSelected methods to execute stubs that handle the new Menu Items.

7.1. Start by overriding onOptionsItemSelected to handle the Activity menu selections. For the remove menu option, you can use the getSelectedItemPosition method on the List View to find the currently highlighted item.

@Override

public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item);

int index = myListView.getSelectedItemPosition();

switch (item.getItemId()) {

case (REMOVE_TODO): {

if (addingNew) {

cancelAdd();

}

else {

removeItem(index);

}

return true;

}

case (ADD_NEW_TODO): {

addNewItem();

return true;

}

}

return false;

}

7.2. Next override onContextItemSelected to handle Context Menu Item selections. Note that you are using the AdapterView specific implementation of ContextMenuInfo. This includes a reference to the View that triggered the Context Menu and the position of the data it’s displaying in the underlying Adapter.

Use the latter to find the index of the item to remove.

@Override

public boolean onContextItemSelected(MenuItem item) { super.onContextItemSelected(item);

switch (item.getItemId()) {

case (REMOVE_TODO): {

AdapterView.AdapterContextMenuInfo menuInfo;

menuInfo =(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();

myEditText.setOnKeyListener(new OnKeyListener() {

public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN)

if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)

{

todoItems.add(0, myEditText.getText().toString());

myEditText.setText(“”);

aa.notifyDataSetChanged();

cancelAdd();

return true;

}

return false;

}

});

Finally, to ensure a consistent UI, modify the main.xml layout to hide the text entry box until the user chooses to add a new item.

<EditText

android:id=”@+id/myEditText”

android:layout_width=”fill_parent”

android:layout_height=”wrap_content”

android:text=””

android:visibility=”gone”

/>

Running the application should now let you trigger the Activity menu to add or remove items from the list, and a Context Menu on each item should offer the option of removing it.

Summar y

You now know the basics of creating intuitive User Interfaces for Android applications. You learned about Views and layouts and were introduced to the Android menu system.

Activity screens are created by positioning Views using Layout Managers that can be created in code or as resource files. You learned how to extend, group, and create new View-based controls to provide customized appearance and behavior for your applications.

In this chapter, you:

❑ Were introduced to some of the controls and widgets available as part of the Android SDK.

❑ Learned how to use your custom controls within Activities.

❑Discovered how to create and use Activity Menus and Context Menus.

❑ Extended the To-Do List Example to support custom Views and menu-based functions.

❑ Created a new CompassView control from scratch.

Having covered the fundamentals of Android UI design, the next chapter focuses on binding application components using Intents, Broadcast Receivers, and Adapters. You will learn how to start new Activities and broadcast and consume requests for actions. Chapter 5 also introduces Internet connectivity and looks at the Dialog class.