ajb468 wrote:
> I am reading a book called "Professional Android Development" and in
> it is an example ToDoList project. The project contains the following
> code:
>
> myEditText.setOnKeyListener(new View.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());
> aa.notifyDataSetChanged();
> myEditText.setText("");
> return true;
> }
> return false;
> }
> } );
>
> There are a few questions that I have about this sample code that I
> don't understand:
>
> First, how can you create a new View.OnKeyListener because I thought
> you couldn't instantiate interfaces?
This code is creating an instance of an anonymous inner class that
implements the interface.
> Would it be better or even
> possible to do create the same code by implementing OnKeyListener in
> the class?
Possible, yes. "Better" is difficult to answer in the abstract.
> Second, is it good programming practice to pass all that in argument?
> Is that done to make the code efficient?
I tend to make longer anonymous inner classes be private data members:
private View.OnKeyListener onKey=new View.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());
aa.notifyDataSetChanged();
myEditText.setText("");
return true;
}
return false;
}
};
then call myEditText.setOnKeyListener(onKey) where needed. But that's
just me.
--
Mark Murphy (a Commons Guy)
http://commonsware.com | http://twitter.com/commonsguy
_Android Programming Tutorials_ Version 2.0 Available!
--
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
To unsubscribe from this group, send email to
android-beginners+unsubscribegooglegroups.com or reply to this email with the
words "REMOVE ME" as the subject.