¿Rellenar una vista de lista usando una ArrayList?


Mi aplicación Android necesita rellenar el ListView utilizando los datos de un ArrayList.

Tengo problemas para hacer esto. ¿Puede alguien ayudarme con el código?

Author: God, 2011-02-21

4 answers

Necesita hacerlo a través de un ArrayAdapter que adaptará su ArrayList (o cualquier otra colección) a sus elementos en su diseño (ListView, Spinner, etc.).).

Esto es lo que dice la guía para desarrolladores de Android :

Un ListAdapter que administra un ListView respaldado por una matriz de objetos arbitrarios. De forma predeterminada, esta clase espera que el id de recurso proporcionado haga referencia a un único TextView. Si desea utilizar un diseño más complejo, utilice los constructores que también toman un id de campo. Ese id de campo debe hacer referencia a TextView en el recurso de diseño más grande.

Sin embargo, el TextView se hace referencia, se rellenará con el toString() de cada objeto en la matriz. Puede agregar listas o matrices de objetos personalizados. Sobreescriba el método toString() de sus objetos para determinar qué texto se mostrará para el elemento de la lista.

Para usar algo que no sea TextViews para la visualización del array, por ejemplo ImageViews, o para que algunos de los datos además de toString() los resultados llenen las vistas, override getView(int, View, ViewGroup) para devolver el tipo de vista que desea.

Así que tu código debería verse como:

public class YourActivity extends Activity {

    private ListView lv;

    public void onCreate(Bundle saveInstanceState) {
         setContentView(R.layout.your_layout);

         lv = (ListView) findViewById(R.id.your_list_view_id);

         // Instanciating an array list (you don't need to do this, 
         // you already have yours).
         List<String> your_array_list = new ArrayList<String>();
         your_array_list.add("foo");
         your_array_list.add("bar");

         // This is the array adapter, it takes the context of the activity as a 
         // first parameter, the type of list view as a second parameter and your 
         // array as a third parameter.
         ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                 this, 
                 android.R.layout.simple_list_item_1,
                 your_array_list );

         lv.setAdapter(arrayAdapter); 
    }
}
 208
Author: Amokrane Chentir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-14 17:54:53

Paso a paso tutorial

También busque ArrayAdapter interfaz:

ArrayAdapter(Context context, int textViewResourceId, List<T> objects)
 11
Author: Sanjit Saluja,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-29 03:21:58

Pruebe la siguiente respuesta para rellenar listview usando ArrayList

public class ExampleActivity extends Activity
{
    ArrayList<String> movies;

    public void onCreate(Bundle saveInstanceState)
    {
       super.onCreate(saveInstanceState);
       setContentView(R.layout.list);

       // Get the reference of movies
       ListView moviesList=(ListView)findViewById(R.id.listview);

       movies = new ArrayList<String>();
       getMovies();

       // Create The Adapter with passing ArrayList as 3rd parameter
       ArrayAdapter<String> arrayAdapter =      
                 new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, movies);
       // Set The Adapter
       moviesList.setAdapter(arrayAdapter); 

       // register onClickListener to handle click events on each item
       moviesList.setOnItemClickListener(new OnItemClickListener()
       {
           // argument position gives the index of item which is clicked
           public void onItemClick(AdapterView<?> arg0, View v,int position, long arg3)
           {
               String selectedmovie=movies.get(position);
               Toast.makeText(getApplicationContext(), "Movie Selected : "+selectedmovie,   Toast.LENGTH_LONG).show();
           }
        });
    }

    void getmovies()
    {
        movies.add("X-Men");
        movies.add("IRONMAN");
        movies.add("SPIDY");
        movies.add("NARNIA");
        movies.add("LIONKING");
        movies.add("AVENGERS");   
    }
}
 6
Author: KarthikKPN,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-19 14:36:38
public class Example extends Activity
{
    private ListView lv;
    ArrayList<String> arrlist=new ArrayList<String>();
    //let me assume that you are putting the values in this arraylist
    //Now convert your arraylist to array

    //You will get an exmaple here

    //http://www.java-tips.org/java-se-tips/java.lang/how-to-convert-an-arraylist-into-an-array.html 

    private String arr[]=convert(arrlist);
    @Override
    public void onCreate(Bundle bun)
    {
        super.onCreate(bun);
        setContentView(R.layout.main);
        lv=(ListView)findViewById(R.id.lv);
        lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , arr));
        }
    }
 2
Author: Tanmay Mandal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-02 11:25:18