Sergio Sergio - 1 month ago 9
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;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adaptador = new ArrayAdapter<Categoria>(this, android.R.layout
.simple_list_item_1, lista);
view_lista = (ListView)findViewById(R.id.view_lista);
view_lista.setAdapter(adaptador);


And this is the simple_list_item_1 layout:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:minHeight="?android:attr/listPreferredItemHeightSmall" />


Thanks :)

Answer

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 {
  ...

    @Override
    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.