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.
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.
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.
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.
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.
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);
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With