Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implement android:src="@drawable/image" programmatically in Android

I am trying to set the foreground image on an image button. After some research, I came across this code sample:

<ImageButton android:text="Button" android:id="@+id/button1"     android:layout_width="wrap_content"      android:layout_height="wrap_content"     android:src="@drawable/icon"/> 

My query is how to actually implement android:src in code.

like image 450
user788511 Avatar asked Sep 08 '11 10:09

user788511


People also ask

How to add drawable image in android?

Drag and drop your images directly onto the Resource Manager window in Android Studio. Alternatively, you can click the plus icon (+), choose Import Drawables, as shown in figure 3, and then select the files and folders that you want to import. Figure 3: Select Import Drawables from the dropdown menu.

How to use drawable image in android?

To use an image resource, add your file to the res/drawable/ directory of your project. Once in your project, you can reference the image resource from your code or your XML layout. Either way, it's referred to using a resource ID, which is the file name without the file type extension. For example, refer to my_image.

How to add image in drawable XML in android?

Step 1: In this method first of all in your system find your required images and copy the image as we do normally. Step 2: Then open the Android Studio go to the app > res > drawable > right-click > Paste as shown in the below figure. Step 3: Then a pop-up screen will arise like below.

How to add image in XML Android Studio?

xml (or any activity you need to add image) and select the Design view. There you can see your Palette tool box on left side. You need to drag and drop ImageView. Select the image you want press Ok you can see the image on the Design view.


2 Answers

Try this:

ImageButton btn = (ImageButton)findViewById(R.id.button1); btn.setImageResource(R.drawable.newimage); 

where newimage is the image name in drawable folder.

EDITED
try this:

ImageButton btn = (ImageButton)findViewById(R.id.button1); btn.setImageBitmap(bm); 

where bm is bitmap extracted from server.

EDITED AGAIN
I see you receive a Drawable; well, do this:

normalImage = Drawable.createFromStream(code); Bitmap bm = ((BitmapDrawable)normalImage).getBitmap(); ImageButton btn = (ImageButton)findViewById(R.id.button1); btn.setImageBitmap(bm); 
like image 156
Marco Avatar answered Oct 04 '22 08:10

Marco


Here's what worked for me in setting the image:src on an ImageButton programmatically** or through code:

1.Retrieve the image drawable.

Drawable tempImage = getResources().getDrawable(R.drawable.my_image); 

2.Get the view.

ImageButton tempButton = (ImageButton)findViewById(R.id.my_image_button); 

3.Set the image for the view.

tempButton.setImageDrawable(tempImage); 

Hope this works for you too!

like image 33
KarenAnne Avatar answered Oct 04 '22 08:10

KarenAnne