Introduction
Lists of related items are needed for almost every app. An example of this is your Gmail app, which displays a scrollable list of messages. To add this functionality to your app, make use of the Android ListView
component.
In this tutorial, you will build an app that uses ListView
to display a list of data. By the end, you will have a good understanding of ListView
and how to use it in your own apps.
Application Structure
We’ll be building an app with information about different programming languages. The app will contain three activities. The MainActivity will be the top-level activity. From there, the user will navigate to the LanguageCategoryActivity. This will contain a list of programming languages. The third activity will be the LanguageActivity, which will display details of each programming language. The language data will be held in instances of a Java class.
Create the Project
Create a new Android project named Proglist with the company domain name as code.tutsplus.com
. This will make the package name com.tutsplus.code.android.proglist
.
You’ll need an empty activity called MainActivity, and the layout should be activity_main. Make sure to uncheck the Backwards Compatibility (AppCompat) checkbox.
The Language Class
The Language
class will be where the activities get their language data from. Each language will be composed of a name, description, and image resource ID.
In your Android Studio, switch to the Project view and select the com.tutsplus.code.android.
proglist
package, which can be found in the app/src/main/java folder. Right click on it, and then go to New > Java Class. The name of the class should be Language
, and make sure the package name is com.tutsplus.code.android.proglist
. Insert the code below into the file you just created.
package com.tutsplus.code.android.proglist; public class Language { private String name; private String description; private int imageResourceId; public static final Language[] languages = { new Language("JavaScript", "JavaScript, often abbreviated as JS, is a high-level, " + "dynamic, weakly typed, prototype-based, multi-paradigm, and interpreted " + "programming language.", R.drawable.javascript), new Language("Java", "Java is a general-purpose computer programming language that is " + "concurrent, class-based, object-oriented, and specifically designed to have as" + " few implementation dependencies as possible.", R.drawable.java), new Language("Ruby", "Ruby is a dynamic, reflective, object-oriented, general-purpose " + "programming language. It was designed and developed in the mid-1990s by " + "Yukihiro "Matz" Matsumoto in Japan.", R.drawable.ruby) }; private Language(String name, String description, int imageResourceId){ this.name = name; this.description = description; this.imageResourceId = imageResourceId; } public String getName() { return name; } public String getDescription() { return description; } public int getImageResourceId() { return imageResourceId; } public String toString() { return this.name; } }
In the code above, you can see that each Language has a name, description, and image resource ID. The image resource ID refers to language images which will be added soon. We’ve also created a static array, languages
, with some sample data.
We’ve also created a constructor and getters for the private variables. Also note that the string representation of a Language
is its name.
Drawable Files
The class you created refers to three image resources, so you need to add those image files to the project. You should have a folder called drawable in the app/src/main/res folder. If the drawable folder is not there, go ahead and create it from Android Studio. You can do this by selecting res, right clicking on it, and then going to New > Android resource directory. Choose a resource type of drawable, name the folder drawable, and click OK.
Download the files from the tutorial source repo and add each one to the app/src/main/res/drawable folder.
Main Activity Layout
Next, you’ll need to add a list view to your layout using the
element. Then you will add an array of entries to the list view by using an android:entries
attribute—this will be set to an array of strings. The array will be displayed as a list of text views. So your main activity layout should look like this:
The values in the list view are given by the options
array, which is defined in the strings.xml file like this:
Proglist - Languages
- Frameworks
- Tools
You can find the strings.xml file in the app/src/main/java/res/values folder of your project. This will populate the list view with three values: Languages, Frameworks, and Tools.
Responding to Clicks
Items in a list view respond to clicks through an event listener. For this application, you need to create an OnItemClickListener
and implement its onItemClick()
method. The OnItemClickListener
listens for when the items are clicked, and the onItemClick()
method lets you determine how the activity should respond to the click.
In the application, you want to start the LanguageCategoryActivity
when the first item on the list is clicked. Here’s the code to create the listener.
AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView> parent, View view, int position, long id) { if (position == 0) { Intent intent = new Intent(MainActivity.this, LanguageCategoryActivity.class); startActivity(intent); } } };
Insert it inside the onCreate
method.
OnItemClickListener
is a nested class within the AdapterView
class. The parameters passed to onItemClick
give it information about the item that was clicked, such as the item’s view and its position.
After creating the listener, you need to attach it to the list view. This is done using the setOnItemClickListener()
method, passing the listener as an argument. This call should be added just below the listener you created, still inside the onCreate
method.
ListView listView = (ListView) findViewById(R.id.list_options); listView.setOnItemClickListener(itemClickListener);
The above code notifies the listener when an item on the list view is clicked. Without this, the items in your list view would not respond to clicks!
Create the Language Category Activity
This activity will list all the programming languages. Create a new activity called LanguageCategoryActivity
. Let’s start with the layout. Here’s how it should look.
You may notice that the layout above is very similar to the one used for the main activity. In this layout, however, the list data is not specified. That’s because the data has been programmatically specified in the Language class. For data like this, an adapter is used instead.
An adapter acts a bridge between the data source and the list view. For this app, you’ll be making use of array adapters (just one of the several different kinds of adapter).
An array adapter binds arrays to views. In this case, you will bind the Language.languages
array in the list view using an array adapter. Insert the code below inside the onCreate
method of the LanguageCategoryActivity
.
ArrayAdapterlistAdapter = new ArrayAdapter<>(this, android.R.layout .simple_list_item_1, Language.languages); ListView listLanguages = (ListView) findViewById(R.id.list_languages); listLanguages.setAdapter(listAdapter);
This code starts by initializing the array adapter. To initialize the adapter, the type of data contained in the array is specified. You can then inform the adapter of the current activity, a layout resource that specifies how each item in the array should be displayed, and the array itself.
The array adapter is then attached to the list view using the ListView.setAdapter()
method.
Adding Intent to the Language Category Activity
When an item in the LanguageCategoryActivity
is clicked, you want to pass control to another activity that displays the information of that language. This new activity should be called LanguageActivity
.
You need to obtain the ID of the clicked item as an extra piece of information, and pass it to LanguageActivity
. LanguageActivity
will use the ID to obtain the details of the right language.
The code for the intent should be inserted in LanguageCategoryActivity
.
AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener(){ @Override public void onItemClick(AdapterView> parent, View view, int position, long id) { Intent intent = new Intent(LanguageCategoryActivity.this, LanguageActivity.class); intent.putExtra(LanguageActivity.EXTRA_LANGUAGEID, (int) id); startActivity(intent); } };
Here, you start by obtaining the ID of the clicked item. This will be added to the LanguageActivity
when it is created.
In the onCreate
method, you’ll also need to assign the listener to the list view like so.
listLanguages.setOnItemClickListener(itemClickListener);
Create the Language Activity
Create a new activity named LanguageActivity
. Replace the contents of the layout with what you have below.
This layout contains two text views and an image view. The information to be displayed in those views will be retrieved from the Intent that launches the activity.
Update your LanguageActivity
class to look like the following:
package com.tutsplus.code.android.proglist; import android.app.Activity; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; public class LanguageActivity extends Activity { //1 public static final String EXTRA_LANGUAGEID = "languageId"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_language); //2 int languageId = (Integer)getIntent().getExtras().get(EXTRA_LANGUAGEID); Language language = Language.languages[languageId]; //3 TextView name = (TextView) findViewById(R.id.name); name.setText(language.getName()); //4 TextView description = (TextView) findViewById(R.id.description); description.setText(language.getDescription()); //5 ImageView photo = (ImageView) findViewById(R.id.photo); photo.setImageResource(language.getImageResourceId()); photo.setContentDescription(language.getName()); } }
Here’s how it works:
- The key that the language id was encoded with in
LanguageCategoryActivity
is defined. - When the
LanguageActivity
is started with the intent fromLanguageCategoryActivity
, the id of the language is retrieved with the intent. After retrieving the information from the intent, you use thegetIntent()
method to obtain extra information about the language.languageId
is the ID of the language. - Populate the name of the language.
- Populate the description of the language.
- Populate the language image.
Now run your app to see what you have built!
Here is a preview of the app.
Conclusion
ListView
is a very important and useful component for building Android apps, so understanding how to use it is important in your Android development journey. Now that you know how to use a ListView
with static list items and how to use an adapter to wire up dynamic items, there’s nothing stopping you! Get out there and build some amazing apps.
And while you’re here, check out some of our other Android app tutorials here on Envato Tuts+!
-
AndroidHow to Get Started With Push Notifications On Android
-
App Templates15 Best Android App Templates of 2017
-
AndroidHow to Solve Android’s 13 Most Common Error Messages
-
Android SDKHow to Upload Images to Firebase from an Android App
Powered by WPeMatico