- Create a new project named TouristInfo. Leave the layout file name as
activity_main.xml and
the activity file as MainActivity.java.
- Change the layout to LinearLayout. Set the orientation attribute to
"vertical". (You could leave the layout as
ConstraintLayout, but this
would make setting the attributes for the ListView container more difficult.)
- Add a TextView widget to the linear layout with the text "Select a city for tourist information".
- Add a ListView container to the linear layout below the textview:
<ListView
android:id="@+id/lv_cities"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
The city names will be added to the listview dynamically.
- Add this code to the end of the onCreate method of the
MainActivity class:
ListView lv = findViewById(R.id.list_cities);
ArrayList<String> cities = new ArrayList<String>( );
// Replace these cities with cities of your choice.
cities.add("Barcelona");
cities.add("London");
cities.add("Paris");
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, cities);
lv.setAdapter(listAdapter);
- Run the app to test it.
- Add three more activities to the project:
Activity Name | Layout | Activity File |
Barcelona | activity_barcelona.xml |
BarcelonaActivity.java |
London | activity_london.xml |
LondonActivity.java |
Paris | activity_paris.xml |
ParisActivity.java |
- Place one JPG image for each city in the app/src/main/res/drawable
folder:
sagradafamilia.jpg
bigben.jpg
eiffeltower.jpg
- On each new layout file, place TextView and
ImageView widgets. Display stub text in each textview, for example:
"Barcelona tourist info." Place the corresponding image from Item 8 in the image view.
- Add this inner class definition to the MainActivity code to create
a private inner class:
private class MyItemListener implements AdapterView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> lv, View itemView,
int position, long id) {
Intent intent = null;
switch(position) {
case 0:
intent = new Intent(MainActivity.this,
BarcelonaActivity.class);
break;
case 1:
intent = new Intent(MainActivity.this,
LondonActivity.class);
break;
case 2:
intent = new Intent(MainActivity.this,
ParisActivity.class);
break;
}
startActivity(intent);
}
}
- Add this line to the end of the onCreate method, after the code in Item 9:
lv.setOnItemClickListener(new MyItemListener( ));
- Here are the source code files:
Layout Files: activity_main.xml
activity_barcelona.xml
activity_london.xml
activity_paris.xml
Java Activity file: MainActivity.xml (Use auto-generated activity files for other activities.)
Manifest file: (For reference only) AndroidManifest.xml