Creating an Activity class

To create a screen we will be extending the base class, as we did in chapter 1, and overriding the key methods it defines. Listing 3.1 shows the first portion of the RestaurantFinder ReviewCriteria class.

Listing 3.1 The first half of the ReviewCriteria Activity class public class ReviewCriteria extends Activity { <-© Extend private static final int MENU_GET_REVIEWS = Menu. FIRST; private Spinner cuisine;

private Button grabReviews; | Q Define Views private EditText location;

@Override public void onCreate (Bundle savedInstanceState) { <—© Override onCreate() super.onCreate(savedInstanceState);

this.setContentView(R.layout.review_criteria); <-1

Define layout with this.location = (EditText)

findViewById( ; <h this.cuisine = (Spinner)

f indViewById(R. id. cuisine) ; <—i© Inflate views this.grabReviews = (Button)

I from XML

findViewById(; <-'

ArrayAdapter<String> cuisines =

new ArrayAdapter<String> (this, R. layout. spinner_view, Define getResources () . I ArrayAdapter getStringArray (R. array. cuisines) ) ; <1-' lnstance cuisines.setDropDownViewResource(

R. layout. spinner_view_dropdown) ; <1-1 Set View for this, cuisine. setAdapter (cuisines) ; <—© Use Adapter © dmpdown this.grabReviews.setOnClickListener( new OnClickListener() { < | Add Button public void onClick (View v) { © OnClickListener handleGetReviews();

The ReviewCriteria class extends B, which does a number of very important things: it gives our application a context, because Activity itself extends; it brings the Android lifecycle methods into play; it gives the framework a hook to start and run your application; and it provides a container into which View elements can be placed.

Because an Activity represents an interaction with the user, it needs to provide components on the screen. This is where views come into play. In our ReviewCriteria class we have referenced three views in the code: location, cuisine, and grabReviews ©. Location is a type of View known as an EditText, a basic text-entry component. Next, cuisine is a fancy select list component, known in Android terms as a Spinner, and grabReviews is a Button.

View elements such as these are placed within an Activity using a particular layout to create a screen. Layout and views can be defined directly in code or in a layout XML resource file. You will learn more about views as we progress through this section, and we will focus specifically on layout in section 3.2.5.

0 0

Post a comment