Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Image of ImageView programmatically in Android

When I change the image programmatically‎, it shows new image on top of the old image which is set originally in layout file?

Here is a snippet of my layout file:

<LinearLayout     android:layout_width="match_parent"     android:layout_height="39dp"     android:gravity="center_vertical" >     <ImageView         android:id="@+id/qStatusImage"         android:layout_width="16dp"         android:layout_height="16dp"         android:layout_margin="5dp"         android:background="@drawable/thumbs_down"          />      <TextView         android:id="@+id/grp_child"         android:layout_width="fill_parent"         android:layout_height="fill_parent"         android:textColor="@color/radio_colors"         android:textStyle="normal"         android:background="@color/grey"     />   </LinearLayout> 

And the code that sets the imageView:

     @Override public View getChildView(final int groupPosition, final int childPosition,         boolean isLastChild, View convertView, ViewGroup parent) { //Answers             if(answersGroup != null)                    answersGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {                        @Override                     public void onCheckedChanged(RadioGroup group, int checkedId) {                           //  int index = answersGroup.indexOfChild(findViewById(answersGroup.getCheckedRadioButtonId()));                             qImageView = (ImageView) V.findViewById(R.id.qStatusImage);                            if(ans ==0 || ans == 5){                             //   qSV.setImageResource(0);                                qImageView.setImageResource(R.drawable.thumbs_up);                            }                            else                                qImageView.setImageResource(R.drawable.thumbs_down);                         }                    }); 

What am I missing?

like image 424
user1529412 Avatar asked Jun 03 '13 21:06

user1529412


People also ask

How do I change the source of a picture on android?

Using setBackgroundResource() method: myImgView. setBackgroundResource(R.

Which file do you alter the image displayed by the ImageView in?

ImageView imageView = new ImageView(this); Bitmap bImage = BitmapFactory. decodeResource(this. getResources(), R. drawable.


2 Answers

That happens because you're setting the src of the ImageView instead of the background.

Use this instead:

qImageView.setBackgroundResource(R.drawable.thumbs_down); 

Here's a thread that talks about the differences between the two methods.

like image 197
Voicu Avatar answered Sep 22 '22 21:09

Voicu


Use in XML:

android:src="@drawable/image" 

Source use:

imageView.setImageDrawable(ContextCompat.getDrawable(activity, R.drawable.your_image)); 
like image 32
fe_araujo_ Avatar answered Sep 20 '22 21:09

fe_araujo_