Listening for List View Events

You need to listen for and respond to specific events within the ListView control. Although there are a number of events to choose from, you are most interested in the event that occurs when a user clicks an item in the ListView control.

To listen for item clicks, you use the setOnItemClickListener() method of the ListView. Specifically, you implement the onItemClick() method of the AdapterView.OnItemClickListener class, like this:

menuList.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View itemClicked, int position, long id) {

TextView textView = (TextView) itemClicked; String strText = textView.getText().toString(); if (strText.equalsIgnoreCase(getResources().getString( R.string.menu_item_play))) { // Launch the Game Activity startActivity(new Intent(QuizMenuActivity.this, QuizGameActivity.class));

} else if (strText.equalsIgnoreCase(getResources().getString( R.string.menu_item_help))) { // Launch the Help Activity startActivity(new Intent(QuizMenuActivity.this, QuizHelpActivity.class)); } else if (strText.equalsIgnoreCase(getResources().getString( R.string.menu_item_settings))) { // Launch the Settings Activity startActivity(new Intent(QuizMenuActivity.this, QuizSettingsActivity.class)); } else if (strText.equalsIgnoreCase(getResources().getString( R.string.menu_item_scores))) { // Launch the Scores Activity startActivity(new Intent(QuizMenuActivity.this, QuizScoresActivity.class));

The onItemClick() method passes in all the information needed to determine which item was clicked. In this case, one of the simplest ways is to cast the view clicked to a TextView control (because you know all items are TextView controls, although you might want to verify this by using instanceof) and just extract the specific Text control and map it to the appropriate screen. Another way to determine which item was clicked would be to check the View control's id attribute.

Now if you implement the OnItemClickListener() method and rerun the application in the emulator, you can use the main menu to transition between the screens in the Been There, Done That! application.

0 0

Post a comment