ToDo List Example Continued

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 earlier in this chapter.

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

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

import android.view.Menu; import android.view.Menuitem;

Prepared for ASHLEE KABAT, email: [email protected] Order number: 56760408 This PDF is for the purchaser's personal use in accordance with the Wrox Terms of Service and under US copyright as stated on this book's copyright page. If you did not purchase this copy, please visit www.wrox.com to purchase your own copy.

import android.view.ContextMenu; import android.widget.AdapterView;

2. 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;

3. Now override the onCreateOptionsMenu method to add two new Menu Items, one to add and the other to remove a 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 hardware menu button will display the menu as shown in Figure 4-10.

4. Having populated the Activity Menu, create a Context Menu. First, modify onCreate to register the List View to use a Context Menu. Then override onCreateContextMenu to populate the Context Menu with a remove item.

@Override public void onCreate(Bundle savedInstanceState) {

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

FIGURE 4-10

@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);

5. Now modify the appearance of the Menu based on the application context. Override the onPrepareOptionsMenu method; the Menu Item should be customized to show Cancel rather than Delete if you are currently adding a new to-do 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;

6. 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 savedInstanceState) { super.onCreate(savedInstanceState); 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;

aa = 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);

7. Next you need to handle Menu Item clicks. Override the onOptionsitemSelected and onContextltemSelected 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 Item you can use the getSelectedltemPosition method on the List View to find the currently highlighted item.

©Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsltemSelected(item);

int index = myListView.getSelectedItemPosition();

switch (item.getItemId()) { case (REMOVE_TODO): { if (addingNew) { cancelAdd();

removeItem(index);

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 index of the data it's displaying from the underlying Adapter.

Use the latter as the index of the item to remove. ©Override public boolean onContextItemSelected(MenuItem item) { super.onContextItemSelected(item);

AdapterView.AdapterContextMenuInfo menuInfo;

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

int index = menuinfo.position;

removeitem(index); return true;

return false;

7.3. Create the stubs called in the Menu Item selection handlers you created earlier.

private void cancelAdd() { }

private void addNewitem() { }

private void removeitem(int _index) { }

8. Now implement each of the stubs to provide the new functionality.

private void cancelAdd() { addingNew = false;

myEditText.setVisibility(View.GONE);

private void addNewitem() { addingNew = true;

myEditText.setVisibility(View.VISIBLE); myEditText.requestFocus();

private void removeitem(int _index) { todoItems.remove(_index); aa.notifyDataSetChanged();

9. You need to hide the text entry box after you've added a new to-do item. In the onCreate method modify the onKeyListener to call the cancelAdd function after adding a new item.

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;

10. 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"

All code snippets in this example are part of the Chapter 4 Todo List 2 project, available for download at Wrox.com.

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.

SUMMARY

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.

You learned to create Activity screens 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 a 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 Views within Activities.

> Discovered how to create dynamic Drawable resources in XML.

> Learned how to create UIs that are resolution- and pixel-density-independent.

> 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 Compass View control from scratch.

Now that we've 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 action. Chapter 5 also introduces Internet connectivity and looks at the Dialog class.

Mobile Apps Made Easy

Mobile Apps Made Easy

Quick start guide to skyrocket your offline and online business success with mobile apps. If you know anything about mobile devices, you’ve probably heard that famous phrase coined by one of the mobile device’s most prolific creators proclaiming that there’s an app for pretty much everything.

Get My Free Training Guide


Post a comment