Android Programming Tutorials

(Romina) #1
A Simple Form

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button save=(Button)findViewById(R.id.save);

save.setOnClickListener(onSave);
}

private View.OnClickListener onSave=new View.OnClickListener() {
public void onClick(View v) {
EditText name=(EditText)findViewById(R.id.name);
EditText address=(EditText)findViewById(R.id.addr);

r.setName(name.getText().toString());
r.setAddress(address.getText().toString());
}
};
}

Here, we:



  • Create a single local restaurant instance when the activity is


instantiated



  • Get our Button from the Activity via findViewById(), then connect it


to a listener to be notified when the button is clicked



  • In the listener, we get our two EditText widgets via findViewById(),


then retrieve their contents and put them in the restaurant


This code sample shows the use of an anonymous inner class


implementation of a View.OnClickListener, named onSave. This technique is


used in many places throughout this book, as it is a convenient way to


organize bits of custom code that go into these various listener objects.


Then, run the ant install command to compile and update the emulator.


Run the application to make sure it seems like it runs without errors,


though at this point we are not really using the data saved in the restaurant


object just yet.


Extra Credit..................................................................................................


Here are some things you can try beyond those step-by-step instructions:


16
Free download pdf