I am creating a sample example from a book. Its called "To Do List."
I'm at the point where I am working with the Options menu. I have the
options of adding and removing an item to a list. I can add items to a
list but every time I remove an item, the program "Stopped
Unexpectedly." Everything in my code seems to be fine. Ill show a few
sections of the code that have to do with the view.
static final private int ADD_NEW_TODO = Menu.FIRST;
static final private int REMOVE_TODO = Menu.FIRST + 1;
private boolean addingNew = false; // True if myEditText is visible.
False if not.
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);
myListView = (ListView) findViewById(R.id.myListView);
myEditText = (EditText) findViewById(R.id.myEditText);
todoItems = new ArrayList<String>();
int resID = R.layout.todolist_item;
final ArrayAdapter<String> aa;
aa = new ArrayAdapter<String>(this, resID, todoItems);
myListView.setAdapter(aa);
registerForContextMenu(myListView);
myEditText.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent
event) {
if (event.getAction() == KeyEvent.ACTION_DOWN)
if (keyCode == KeyEvent.KEYCODE_1) {
todoItems.add(0,
myEditText.getText().toString());
myEditText.setText("");
aa.notifyDataSetChanged();
cancelAdd();
return true;
}
return false;
}
});
}
@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;
}
@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;
}
private void removeItem(int _index) {
todoItems.remove(0);
aa.notifyDataSetChanged();
}
--
You received this message because you are subscribed to the Google
Groups "Android Beginners" group.
NEW! Try asking and tagging your question on Stack Overflow at
http://stackoverflow.com/questions/tagged/android
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-beginners?hl=en