我正在尝试在图像按钮上设置前景图像。经过一些研究,我找到了这个代码示例:
<ImageButton android:text="Button" android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/icon"/>
我的问题是如何在代码中实现android:src。
我正在尝试在图像按钮上设置前景图像。经过一些研究,我找到了这个代码示例:
<ImageButton android:text="Button" android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/icon"/>
我的问题是如何在代码中实现android:src。
尝试这样做:
ImageButton btn = (ImageButton)findViewById(R.id.button1);
btn.setImageResource(R.drawable.newimage);
其中newimage
是drawable文件夹中的图像名称。
编辑
尝试这个:
ImageButton btn = (ImageButton)findViewById(R.id.button1);
btn.setImageBitmap(bm);
其中bm是从服务器提取的位图。
再次编辑
我看到你收到了一个Drawable;好的,做这个:
normalImage = Drawable.createFromStream(code);
Bitmap bm = ((BitmapDrawable)normalImage).getBitmap();
ImageButton btn = (ImageButton)findViewById(R.id.button1);
btn.setImageBitmap(bm);
以下是我在编程时如何通过代码为ImageButton
设置image:src
的方法:
1.获取图像可绘制对象。
Drawable tempImage = getResources().getDrawable(R.drawable.my_image);
2. 获取视图。
ImageButton tempButton = (ImageButton)findViewById(R.id.my_image_button);
3.设置视图的图像。
tempButton.setImageDrawable(tempImage);
希望这对你也有用!
ImageButton button1=(ImageButton)findViewById(R.id.button1);
button1.setImageResource(R.drawable.icon);
试试这个:
ImageButton tran_btn_skip;
tran_btn_skip = (ImageButton) findViewById(R.id.btn);
try {
Bitmap bitmap_skip = BitmapFactory.decodeStream((InputStream) new URL(
"http://233.129.115.55/MRESC/images/test/skip.png")
.getContent());
tran_btn_skip.setImageBitmap(bitmap_skip);
} catch (Exception e) {
}
另一种简短的变体
views.setImageViewResource(R.id.button1, R.drawable.newbutton);
我知道这是一个老问题,但是为了未来的搜索... 我相信你正在寻找的是:
imgButton.setImageDrawable(drawable);