Michał
Michał

Reputation: 655

Get access to particular item's layout in list view

In my android app my Main Activity extends List Activity. I store there elements called Items, their layout is defined by itemLayout xml file and I use custom adapter (called ItemAdapter) to transfer data to List View in Main Activity. In itemLayout there's an ImageView and my aim is to change its image when user clicks on the particular item in list view. In my opinion the easiest way to achieve that is to get access to particular item's (the one that was clicked) layout, there find the ImageView and call method setImageBitmap. How can I "find" this layout of clicked item? I tried many things in method:

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

}

but nothing worked. Do I have to add anything to my ItemAdapter? Or is it possible to do in onListItemClick(…) but I can't find out how?

Upvotes: 1

Views: 3914

Answers (4)

Quick learner
Quick learner

Reputation: 11457

Yes It is possible in your custom adapter class in the getView() mtheod u can change imageview bitmap by clicking on it

see this code

@Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        View rowView = convertView;
        rowView = inflater.inflate(R.layout.playlist_item, null);

        final ImageView im = (ImageView) rowView.findViewById(R.id.favorite);
        im.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                // Do your stuff here

            }
        });

        return rowView;
    }

Upvotes: 0

Ifrit
Ifrit

Reputation: 6821

You're thinking about it in slightly the wrong way. Adapter's are a way to map data to views. So if you want to change how a particular view looks for a given position, you need to change it's correlating data so that the rendered View then changes. Attempting to modify a view directly kinda goes against how adapters are meant to be used.

So in your case, when a user clicks on an item. Find that item in your adapter via the position number. Then update the item and ensure notifydataset is called. Meanwhile, your adapter's getView() will then handle displaying the appropriate image.

Upvotes: 4

Blackbelt
Blackbelt

Reputation: 157437

onListItemClick is fired when you press on an element of the ListView. If you want to retrieve the element in the dataset, you can simply invoke

l.getItemAtPosition(position)

the returned value has to be casted to the specific object

Upvotes: 0

nister
nister

Reputation: 171

As I understood you need to modify clicked item layout, right? Use argument from onListItemClicked:

v.findViewById(<your_img_view_id>)

For better performance use view holder.

Upvotes: 0

Related Questions