Reputation: 4063
I'm learning Android, I'm coming from .net Currently I'm still exploring and learning the basics. As a simple test I wanted to try this: - make a Person class (with string firstname & string lastname), - make few objects - display these in a spinner
So far so good, but I would like to see the firstname in the spinner. I couldn't figure out how this works, where you can actually say: "From these objects, display the firstname string"
My person class is this:
public class Person {
public String FirstName;
public String LastName;
public Person(String firstName, String lastName){
this.FirstName = firstName;
this.LastName = lastName;
}
public String ToString()
{
return FirstName + " "+LastName;
}
}
And my mainclass in oncreate:
Person p1 = new Person("Dave", "Hannes");
Person p2 = new Person("Roos", "Gijbels");
Person p3 = new Person("Thomas", "Beerten");
List<Person> personenLijst = new ArrayList<Person>();
personenLijst.add(p1);
personenLijst.add(p2);
personenLijst.add(p3);
ArrayAdapter<Person> personenAdapter = new ArrayAdapter<Person>(
this,
android.R.layout.simple_spinner_dropdown_item,
personenLijst
);
Spinner spinner = (Spinner)findViewById(R.id.spinner);
spinner.setAdapter(personenAdapter);
Upvotes: 0
Views: 59
Reputation: 43023
If you're using ArrayAdapter
, it uses toString()
method to get the display string for each object.
From Android documentation on ArrayList
However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.
Generic ArrayAdapter
is a simple class, if you want to control your display better, you can create your own class extending ArrayAdapter
.
Note that you have wrong casing for your toString()
, method (I guess it's natural coming from .NET). Methods in Java start with lower case:
public String toString()
{
return FirstName; // to return only first name
}
Upvotes: 2