Android: Change the source of ImageView present in ListView

Posted by Vivek on Stack Overflow See other posts from Stack Overflow or by Vivek
Published on 2010-12-26T11:41:20Z Indexed on 2010/12/26 11:54 UTC
Read the original article Hit count: 367

Filed under:
|
|

Hi All,

I have a ListView specified by list_item.xml Now I need to change the Image in my list inside onListItemClick. How to achieve this?

//list_item.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/play" 
android:id="@+id/img"
/> 
<TextView 
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:id="@+id/txt"
/>
</LinearLayout>

I have a Custom Adapter to populate my list. Code below is the adapter.

    public class MyCustomAdapter extends ArrayAdapter<String> {
public MyCustomAdapter(Context context, int textViewResourceId,
  String[] objects) {
 super(context, textViewResourceId, objects);
 // TODO Auto-generated constructor stub
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
 // TODO Auto-generated method stub
 LayoutInflater inflater=getLayoutInflater();
 View row=inflater.inflate(R.layout.list_item, parent, false);
 TextView label=(TextView)row.findViewById(R.id.txt);
 label.setText(Sounds[position]);
 ImageView icon=(ImageView)row.findViewById(R.id.img);
     icon.setMaxHeight(32);
     icon.setMaxWidth(32);
 icon.setPadding(2, 1, 5, 1);
 icon.setImageResource(R.drawable.play);
 return row;
}
}    

And in onCreate I do the following

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

    try
    {
            setListAdapter(new MyCustomAdapter(this, R.layout.list_item, Sounds));
            //Sounds --> String array 
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
  }

Now when any row is selected, I need to change the image associated with the selected view. Your help is appreciated. Thanks.

© Stack Overflow or respective owner

Related posts about android

Related posts about image