在Android中以编程方式实现android:src ="@ drawable/image"

use*_*511 36 android android-widget android-imageview android-button

我试图在图像按钮上设置前景图像.经过一些研究,我发现了这个代码示例:

<ImageButton android:text="Button" android:id="@+id/button1"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"
    android:src="@drawable/icon"/>
Run Code Online (Sandbox Code Playgroud)

我的查询是如何在代码中实际实现android:src.

Mar*_*rco 97

试试这个:

ImageButton btn = (ImageButton)findViewById(R.id.button1);
btn.setImageResource(R.drawable.newimage);
Run Code Online (Sandbox Code Playgroud)

可绘制文件夹中newimage的图像名称在哪里.

编辑
尝试这个:

ImageButton btn = (ImageButton)findViewById(R.id.button1);
btn.setImageBitmap(bm);
Run Code Online (Sandbox Code Playgroud)

其中bm是从服务器中提取的位图.

再次编辑
我看到你收到了Drawable; 好吧,这样做:

normalImage = Drawable.createFromStream(code);
Bitmap bm = ((BitmapDrawable)normalImage).getBitmap();
ImageButton btn = (ImageButton)findViewById(R.id.button1);
btn.setImageBitmap(bm);
Run Code Online (Sandbox Code Playgroud)


Kar*_*nne 12

以下image:src是以ImageButton编程方式**或通过代码设置的方法:

1.检索可绘制的图像.

Drawable tempImage = getResources().getDrawable(R.drawable.my_image);
Run Code Online (Sandbox Code Playgroud)

2.获取视图.

ImageButton tempButton = (ImageButton)findViewById(R.id.my_image_button);
Run Code Online (Sandbox Code Playgroud)

3.设置视图的图像.

tempButton.setImageDrawable(tempImage);
Run Code Online (Sandbox Code Playgroud)

希望这也适合你!

  • 非常清楚!但请注意,步骤 1 使用的 API 从 API 级别 22 开始已弃用。我将其替换为:ContextCompat.getDrawable(context, R.drawable.my_image)。 (2认同)