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/