Link model information to a ListView correctly

1

To retrieve an object from my domain from the AdapterView.OnItemLongClickListener event bound to my ListView I added to the ViewHolder of the adapter used by it a reference to my domain object.

public static class ViewHolder {
    private TextView descricao;
    private TextView outraInformacao;
    private MeuObjeto meuObjeto;

    public MeuObjeto getMeuObjeto() {
        return meuObjeto;
    }
}

And I proceeded as follows to retrieve this reference:

private AdapterView.OnItemLongClickListener itemLongClickListener = new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

        MeuAdapter.ViewHolder viewHolder = (MeuAdapter.ViewHolder) view.getTag();

        Toast.makeText(context, viewHolder.getMeuObjeto().getId(), Toast.LENGTH_SHORT).show();

        return false;
    }
};

To implement the Adapter I used the ArrayAdapter:

public MeuAdapter extends ArrayAdapter<MeuObjeto> {
    ...
}

My domain class contains simple attributes: String and Long. String attributes are used to render some information, and Long attributes hold primary keys that can be used to retrieve information. To be more exact this class contains ten attributes, two of Long and eight of String.

Is it considered bad practice to include non-view information in a ViewHolder? Is there any negative implication, either for performance issues, or any other that weigh against this approach?

    
asked by anonymous 18.09.2015 / 02:30

1 answer

1

If you want to get the MeuObjeto object that is associated with the ListView clicked item, ArrayAdapter provides the getItem(position) for this.

It can be used in OnItemLongClickListener() this way:

private AdapterView.OnItemLongClickListener itemLongClickListener = new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

        MeuObjeto meuObjeto = (MeuObjeto)parent.getAdapter().getItem(position);

        Toast.makeText(context, meuObjeto.getId(), Toast.LENGTH_SHORT).show();

        return false;
    }
};
    
18.09.2015 / 16:45