Link model information to a Listview correctly

Asked

Viewed 53 times

1

To retrieve an object from my domain from the event AdapterView.OnItemLongClickListener linked to my Listview added to the Viewholder of the Adapter used by this 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 Adapter I used Arrayadapter:

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

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

Is it considered bad practice to include non-view information in a Viewholder? Is there any negative implication, whether for performance reasons, or any other implication against that approach?

  • What information does this object have? What type is your Adapter? It is an Adapter cursor?

  • @ramaral, includes information about the model and Adapter in the question.

1 answer

1


If what you want is to get the object MeuObjeto which is associated with the clicked item of Listview, the Arrayadapter provides the method getItem(position) for that reason.

It can be used in OnItemLongClickListener()(or OnItemClickListener()) in 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;
    }
};
  • I couldn’t use the method getIem(). He is not visible to me, yet the method getItemAtPosition() works perfectly.

  • You’re right, it’s not visible because the call to getAdapter(). Edited response.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.