Sergio Sergio - 10 months ago 54
Android Question

Customed ArrayAdapter

I created a class called Categoria, it has two attributes (String nombre, int id).

I created an ArrayList with elements of type Categoria.

When I show the ArrayList on a ListView, I get this:

enter image description here

Instead of this, I want the attribute nombre, that is a String, to be shown.
The ArrayAdapter must be of the type Categoria, not String.

How can I do this? Maybe creating a customed adapter?

Here is a piece of the code:

public class MainActivity extends AppCompatActivity {

private ArrayList<Categoria> lista;
private ArrayAdapter<Categoria> adaptador;
private ListView view_lista;

protected void onCreate(Bundle savedInstanceState) {
adaptador = new ArrayAdapter<Categoria>(this, android.R.layout
.simple_list_item_1, lista);
view_lista = (ListView)findViewById(;

And this is the simple_list_item_1 layout:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android=""
android:minHeight="?android:attr/listPreferredItemHeightSmall" />

Thanks :)

Answer Source

By default, ArrayAdapter will display the text returned by the toString method of your objects. In this simple case, you can simply override the toString method for Categoria and return the nombre field:

public class Categoria {

    public String toString() {
        return this.nombre;

If your application needs ever change and you require a more complicated layout, you can override the getView method of ArrayAdapter to bind data from Categoria to a more complicated view.