This small library aims to prevent Android developpers from writing the same boring code for Adapters again and again.
Indeed, for Adapters, Google suggest to use the ViewHolder pattern which leads to a very ugly code and a non reusable View.
This library proposes to change the goal of the Adapter. It's no longer an object which builds a View and set the data of the item in the View (calling setText(), setImage(), etc...). But it's an object which chooses a View corresponding to an item and the View itself is responsible for binding the data of the item.
So you have an Adapter which usually do the same thing, so it can be written once (in the library) and used for many items and views. And you have some reusable Views which can be used for a ListVIew and in other parts of your application.
The steps to create a ListView using this library are :
- Create a
Viewand let it implementUAdaptable<I, V>whereIis the class of the item to show andVthe class of the view itself. - Implement the two methods of
UAdaptable:
a.newInstance()which returns anotherView. In most of the cases you just have to call the constructor of the View.
b.bind(I item)which is where you set the data of the item in theView. - Instantiate a
UArrayAdapter<I, V>in yourActivity/Fragmentpassing to it theContext, aListof items, and an instance of theView.
- The
Viewwhich shows an instance ofMyItem
public class MyItemView extends LinearLayout implements UAdaptable<MyItem, MyItemView>
{
private TextView text;
private ImageView image;
public MyItemView(Context context) {
super(context);
init();
}
private void init() {
View.inflate(getContext(), R.layout.myitemview, this);
text = (TextView) findViewById(R.id.myitemview_text);
image = (ImageView) findViewById(R.id.myitemview_image);
}
@Override
public void bind(int position, MyItem item, Adapter adapter) {
text.setText(item.getText());
image.setImageResource(item.getImageResource());
}
@Override
public MyItemView newInstance() {
return new MyItemView(getContext());
}
}- The
Activity/Fragment(ctxrepresents theContext)
UArrayAdapter<MyItem, MyItemView> adapter = new UArrayAdapter<MyItem, MyItemView>(ctx, items, new MyItemView(ctx));
listView.setAdapter(adapter);