English English

Visualizar datos de forma programada en una vista de lista que se puede desplazar.

Here we will learn how to use the ListView class and component to display data in rows as a List view. The list view is scrollable and it can display text, buttons, checkboxes, etc. Data for the list view is loaded through a Java class (an Activity).

We will use here a text view and a check box. The list view uses the model shoppinglist. A shopping list app is used here as an example.

Create Android layout file for the rows of the list

Create the file layout_row.xml with this content:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

This defines the layout of a row of the list view. Later we will create a list of this row layout and access the checkbox component (has the id "checkbox") and the text view (has the id "shoppingitem").

Add List view to the main layout file "activity_main.xml"

This layout file contains only the List View to keep this introduction of ListView easy to understand.
Add the component ListView as shown here:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"


Create Java (model) class "Shopping.java"

Create a Java class that will be used for a List array of the list view. It contains here the boolean variable isMarked, that saves if the checkbox is checked. But this class has also a String variable which saves the name of the shopping item.

public class Shopping {
    private boolean isMarked;
    private String shoppingItem;
    public String getShoppingItem() {
        return shoppingItem;
    public void setShoppingItem(String shoppingItem) {
        this.shoppingItem = shoppingItem;
    public boolean getMarked() {
        return isMarked;
    public void setMarked(boolean marked) {
        isMarked = marked;



Create adapter class "ShoppingAdapter.java"

This class must extend (command "extends") the class "BaseAdapter". It contains the following instance variables: Context variable and ArrayList with the before created "Shopping" class. You must override six functions.
The class contains the following:

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;

public class ShoppingAdapter extends BaseAdapter {
    private Context context;
    public static ArrayList<Shopping> modelShoppingList;
    public ShoppingAdapter(Context context, ArrayList<Shopping> modelShoppingList) {
        this.context = context;
        this.modelShoppingList = modelShoppingList;
    public int getViewTypeCount() {
        return getCount();
    public int getItemViewType(int position) {
        return position;
    public int getCount() {
        return modelShoppingList.size();
    public Object getItem(int position) {
        return modelShoppingList.get(position);
    public long getItemId(int position) {
        return 0;
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder(); LayoutInflater inflater = (LayoutInflater) context
            convertView = inflater.inflate(R.layout.shoppinglistview, null, true);
            holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
            holder.shoppingitem = (TextView) convertView.findViewById(R.id.shoppingitem);
        }else {
            //  Method getTag() creates the viewHolder object as a tag and returns it to the view
            holder = (ViewHolder)convertView.getTag();
        holder.checkBox.setText("Checkbox No. "+position);
        //Save this component in view ID 1
        holder.checkBox.setTag(1, convertView);
        holder.checkBox.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Integer listPosition = (Integer) holder.checkBox.getTag();
                Toast.makeText(context, "You clicked Checkbox "+pos, Toast.LENGTH_SHORT).show();
                //Set display of checkbox
                }else {
        return convertView;
    private class ViewHolder {
        protected CheckBox checkBox;
        private TextView shoppingitemText;

The content of the view is programmed in the function getView(). In the function onClick() (called through a OnClickListener on the checkbox) we define what should happen, if a checkbox is clicked. The component of the layout file (view) layout_row.xml is saved in a holder variable class "holder.checkBox". The holder variable or variables are created in the class ViewHolder in this same file. The view with its content is saved as a tag, which has an ID. Here we use the ID 1.

It is recommended to save the IDs for the view in the file "integer.xml". You have to create that file in the res/values directory. There you can store Integer values, which can be accessed like this in the Java code: "R.integer.YOUR_ID"
An "integer.xml" file looks like this:

<?xml version="1.0" encoding="utf-8"?>
<integer name="MY_INTEGER_VARIABLE">1</integer>

You can also extend some functionality in the function onClick() in the above created class "ShoppingAdapter.java".
If you would like to edit or access components in the list row, then you can call them like this:

//Load view (Shopping list row) and components in view through this command
View shoppingitemRow = (View) holder.checkBox.getTag(1);
TextView shoppingitemTextview = (TextView) shoppingitemRow.findViewById(R.id.shoppingitem); 

The TextView shoppingitemTextview is referencing to the actual row in the row layout view of the created list view for this shopping list app. You can edit now the textview (here the Textname of a shopping item) of the item of a row where its check box was clicked.


Add List View functionality to the main activity class "MainActivity.java"

Add this following code in the class "MainActivity":

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
    private ListView shoppingListView;
    public static ArrayList<Shopping> shoppingListArray;
    private ShoppingAdapter shoppingAdapter;
    private String[] shoppingitemslist = new String[]{"Ice Cream", "Apple", "Chocolate", "Cheese", "Watermelon", "Salad"};
    protected void onCreate(Bundle savedInstanceState) {
        //Create ListView
        shoppingListView = (ListView) findViewById(R.id.shoppinglistview);
        //Configure ListView
        shoppingListArray = createAndGetShoppinglistModel(false);
        shoppingAdapter = new ShoppingAdapter(this, this.shoppingListArray);
    * Creates List of shopping item rows from defined String array "shoppingitemslist"
    private ArrayList<Shopping> createAndGetShoppinglistModel(boolean isSelect){
        ArrayList<Shopping> shoppingList = new ArrayList<>();
        for(int i = 0; i < 6; i++){
            Shopping shopping = new Shopping();
        return list;

The data for the ListView will be added in the function onCreate(), because the ListView will be displayed directly after the app was started. The ListView gets an Adapter (which is here the created "shoppingAdapter") which does manage the data (components, values in rows) of the list view.
Here the List Array "shoppingListArray" that contains the items of the shopping list, will be created from a defined String array "shoppingitemslist".

You can also extend the application to load data from a database. Saving and loading data from database in Android is mentioned in an other tutorial on this site, which you can find here:

If you want to know more about the here used ListView or BaseAdapter, then please visit these sites:

More about ListView:

More about BaseAdapter:



Usamos cookies en nuestro sitio web. Algunas de ellas son esenciales para el funcionamiento del sitio, mientras que otras nos ayudan a mejorar el sitio web y también la experiencia del usuario (cookies de rastreo). Puedes decidir por ti mismo si quieres permitir el uso de las cookies. Ten en cuenta que si las rechazas, puede que no puedas usar todas las funcionalidades del sitio web.