我在 layout
中创建了一个 button
。在 Drawable
文件夹中,我创建了一个名为 btn01_state
的 XML 文件
。 btn01_state.xml
分配给我通过“android:background=@drawable/btn01_state
”创建的按钮
现在,按钮
有一个默认的image
img1。当我单击
按钮
时,image1更改为 img2,一旦我释放单击的鼠标按钮,image2 再次更改为 img1。
我想要做的是,每次点击更改按钮的图像。
举个例子,最初 btn01 有 img01
如果按下 btn01==> 将 btn01 的 img 设置为 img02 并保持 img02 直到再次按下 btn01。现在,btn01 上有 img02。
当按下 btn01 时,将 img01 设置为 btn01。
我希望这能更清楚地说明我想做什么。
btn_selector:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/android_blue"
android:state_pressed="true" />
<item android:drawable="@drawable/ic_launcher"
android:state_focused="true" />
<item android:drawable="@drawable/ic_launcher" />
main.xml
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/btn01"
android:background="@drawable/btn01_state"/>
最佳答案
您可以在代码中轻松完成。
boolean isPressed = false;
button.setOnClickListener(buttonListener);
OnClickListener buttonListener = new OnClickListener() {
@Override
public void onClick(View v) {
if(isPressed)
button.setBackgroundResource(R.drawable.icon1);
else
button.setBackgroundResource(R.drawable.icon2);
isPressed = !isPressed;
}
};
关于android - 如何在每次点击时更改按钮的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10470288/