Skip to content
pyricau edited this page May 25, 2012 · 6 revisions

This is just a simple demonstration of how you could handle Adapters and AdapterViews in a simple way with AndroidAnnotations.

Let's say you have a Person class:

public class Person {
	public final String firstName;
	public final String lastName;

	public Person(String firstName, String lastName) {
		this.firstName = firstName;
		this.lastName = lastName;
	}
}

and a PersonFinder interface:

public interface PersonFinder {
	List<Person> findAll();
}

You want to create a PersonListActivity that lists all the available persons. For that, you'll need a PersonListAdapter that creates the binds the data to the views, and a PersonItemView that is the view for one item in the list.

The PersonItemView will use one TextView for the first name, and one TextView for the last name:

@EViewGroup(R.layout.person_item)
public class PersonItemView extends LinearLayout {

	@ViewById
	TextView firstNameView;

	@ViewById
	TextView lastNameView;

	public PersonItemView(Context context) {
		super(context);
	}

	public void bind(Person person) {
		firstNameView.setText(person.firstName);
		lastNameView.setText(person.lastName);
	}
}

There's a PersonFinder implementation, let's say InMemoryPersonFinder, that is annotated with @EBean. We won't describe this implementation.

The adapter directly manipulates it to bind its data and create the corresponding views:

@EBean
public class PersonListAdapter extends BaseAdapter {

	List<Person> persons;
	
	@Bean(InMemoryPersonFinder.class)
	PersonFinder personFinder;
	
	@RootContext
	Context context;

	@AfterInject
	void initAdapter() {
		persons = personFinder.findAll();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		PersonItemView personItemView;
		if (convertView == null) {
			personItemView = PersonItemView_.build(context);
		} else {
			personItemView = (PersonItemView) convertView;
		}
		
		personItemView.bind(getItem(position));

		return personItemView;
	}
	
	@Override
	public int getCount() {
		return persons.size();
	}

	@Override
	public Person getItem(int position) {
		return persons.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}
}

Using AndroidAnnotations

Questions?

Enjoying AndroidAnnotations

Improving AndroidAnnotations

Clone this wiki locally