Ofek Agmon
Ofek Agmon

Reputation: 5198

android - get item from listview with custom item view

I have a listview in android and the adapter for it looks like this: mRecipes is of type Recipe[].

 Recipe[] mRecipes;


public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub

    super.onActivityCreated(savedInstanceState);

    // set adapter and ListView
    RecipeAdapter adapter = new RecipeAdapter(getActivity(),
            R.layout.listview_item_row, mRecipes);
    mListView = (ListView) getView().findViewById(R.id.lvMainDishes);

    mListView.setAdapter(adapter);
    mListView.setOnItemClickListener(this);
}

As you can see I have a custon XML view for each item in the list.

I want to be able to get the Recipe object from the Recipe Array on the OnItemClick

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    // get the clicked recipe object here

}

any ideas? thnaks!

Upvotes: 3

Views: 1251

Answers (2)

Tadej
Tadej

Reputation: 2921

If you do not wish to have an adapter instance variable, then your onItemClick implementation could look like this:

@Override
public void onItemClick(AdapterView <?> parent, View view, int position, long id) {
    Recipe r = (Recipe) parent.getAdapter().getItem(position);
}

To extend on what Pedro Oliveira said, another standard idiom would be this:

private RecipeAdapter mAdapter;

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    mAdapter = new RecipeAdapter(getActivity(), R.layout.listview_item_row, mRecipes);
    mListView = (ListView) getView().findViewById(R.id.lvMainDishes);
    mListView.setAdapter(adapter);
    mListView.setOnItemClickListener(this);
}

@Override
public void onItemClick(AdapterView <?> parent, View view, int position, long id) {
    Recipe r = (Recipe) mAdapter.getItem(position);
}

You can avoid the cast if you create a getter method in your RecipeAdapter, e.g:

public class RecipeAdapter extends BaseAdapter {

    // Implementation

    public Recipe get(int position) {
        return mRecipe[position]; // or maybe mList.get(position);
    }

}

Then, your onItemClick boils down to:

@Override
public void onItemClick(AdapterView <?> parent, View view, int position, long id) {
    Recipe r = mAdapter.get(position);
}

Upvotes: 3

Maxime
Maxime

Reputation: 1392

You have to define mRecipes as global variable. Then complete your method like that:

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Recipe recipe = Recipe[position];
}

Upvotes: 0

Related Questions