android - 在 ImageButton 中动态更改图像

标签 android imagebutton

XML     
<ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageButton1"
        android:src="@drawable/image1"
        android:onClick="buttonClick"
    />

JAVA
--------------------
public void buttonClick(View v)
{
    Button aButton = (Button)v;
    aButton.setBackgroundResource(R.drawable.image2);
}

这是我到目前为止尝试过的方法,但没有成功......

我希望能够单击按钮并将图像更改为 image2,我还会根据其他变量将其更改为其他图像。我真的被卡住了。我会继续查看其他问题,如果找到答案,我会在此处发布。

最佳答案

您的 buttonClick() 需要修复:

public void buttonClick(View v) 
{
 ImageButton aButton = (ImageButton)v;
 aButton.setImageResource(R.drawable.image2); 
} 

View 是一个 ImageButton,而不是一个 Button。 src 属性通过 setImageResource 更新,而不是 setBackgroundResource。

关于android - 在 ImageButton 中动态更改图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11802893/

相关文章:

安卓 : merging static libraries into single one

android - png图像在android中显示为灰色背景

android - 如何一次播放一种声音?

android - 如何将图像按钮的背景设置为用户拍摄的照片?

android - Ionic 启动画面后出现白屏

android - 从应用商店更新应用后数据库会发生什么情况?

android - 如何在 Android 上制作这样的布局?

android - adb pull命令权限

Android ImageButton 削减图标顶部

python - 如何让两次鼠标点击不互相影响?