Filling a List View Control

Your ListView control needs content. ListView controls can be populated from a variety of data sources, including arrays and databases, using data adapters. In this case, you have a fixed list of four items, so a simple String array is a reasonable choice for your ListView data.

Begin by retrieving an instance of the ListView control just after the setContentView() method call in the onCreate() method of your activity. To populate your ListView control, you must first retrieve it by using the findViewById() method, as follows:

ListView menuList = (ListView) findViewById(R.id.ListView_Menu);

Next, you need to define the String values you will use to populate the TextView items within the ListView control. In this case, you will load the four resource strings representing the choices:

String[] items = { getResources().getString(R.string.menu_item_play), getResources().getString(R.string.menu_item_scores), getResources().getString(R.string.menu_item_settings), getResources().getString(R.string.menu_item_help) };

Now that you have retrieved the ListView control and have the data you want to stuff into it, you need to use a data adapter to map the data to the layout template you created (menu_item.xml). The choice of adapter depends on the type of data being used. In this case, you use ArrayAdapter:

ArrayAdapter<String> adapt = new ArrayAdapter<String>(this, R.layout.menu_item, items);

Next, you need to tell the ListView control to use the adapter: menuList.setAdapter(adapt);

At this point, you can save the QuizMenuActivity.java file and run the Been There, Done That! application in the Android emulator. After the splash screen finishes, the main menu screen should look much like the screen shown in Figure 8.3.

Been There. Done That!

ft MAIM MENU ft Play Game

FIGURE 8.3

The Been There, Done That! splash screen.

If you get tired of watching the splash screen appear when you launch the application, simply modify the AndroidManifest.xml file to launch QuizMenuActivity by default until you are done testing.

Did you Know?

As you can see, the main menu screen is beginning to take shape. However, clicking the menu items doesn't yet have the desired response.

0 0

Post a comment