Android 设置按钮背景图像更改onClick而不编辑xml,因为在某些情况下按钮背景总是单击问题
我尝试在侦听器中使用此代码更改按钮的onClick图像Android 设置按钮背景图像更改onClick而不编辑xml,因为在某些情况下按钮背景总是单击问题,android,android-button,Android,Android Button,我尝试在侦听器中使用此代码更改按钮的onClick图像 public void onClick(View v) { if(v==ButtonName) ButtonName.setImageResource(R.drawable.clicked_button_image); //action code } 按钮的图像以这种方式正确更改,但是如果有人使用Android设备的“后退”按钮,按钮会显示单击的图像(因为
public void onClick(View v) {
if(v==ButtonName)
ButtonName.setImageResource(R.drawable.clicked_button_image);
//action code
}
按钮的图像以这种方式正确更改,但是如果有人使用Android设备的“后退”按钮,按钮会显示单击的图像(因为清楚地显示了上一个活动的最后一个实例)
如果我尝试使用代码:
public void onClick(View v) {
if(v==ButtonName)
ButtonName.setImageResource(R.drawable.clicked_button_image);
ButtonName.setImageResource(R.drawable.unclicked_button_image);
//action code
}
按钮的图像不会改变
我怎样才能解决这个问题?(不编辑xml)。单击“上一步”按钮时,如何更改为“上一步”
@Override
public boolean onRestore()
{
if(unclickedImageDisplayed)
{
ButtonName.setImageResource(R.drawable.unclicked_button_image);
}
}
如果查看,以及活动生命周期,您可以看到,当您返回到活动时,将调用还原时的方法
可能通过在更改按钮背景时更改一个私有变量,例如,通过检查此布尔值,可以通过编程方式更改按钮的背景以使其处于初始状态。要实现此效果,请尝试以下操作:
您必须在drawable文件夹中创建一个新的xml:(我称之为button\u action)
在布局中:
<Button
android:id="@+id/infobtncontact"
style="@style/ButtonNormal"
android:layout_marginTop="10dp"
android:background="@drawable/button_action"
android:src="@drawable/unclicked_button_image" />
可能必须重新启动eclipse才能识别更改
请原谅我的英语太糟糕了 除非您解释为什么要使用此方法,否则您应该真正使用这样的自定义按钮
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/clicked_button_image" /> <!-- pressed -->
<item android:state_focused="true" android:drawable="@drawable/focus_button_image" /> <!-- focused -->
<item android:drawable="@drawable/unclicked_button_image"/> <!-- default -->
</selector>
它是在不修改xml的情况下指定的。该按钮位于另一个类活动中,因此此代码不起作用,因为它将新按钮与未点击的图像关联,并且不会更改上一个活动的按钮。因此,请编辑您的问题以更好地解释它,您没有指定按钮未在实际类中引用,不是吗?那么,在onRestore()事件或onResume()事件上还原未链接的图像如何?我如何解决onRestore()事件或onResume()的问题?你能告诉我你回答的更多细节吗?
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/clicked_button_image" /> <!-- pressed -->
<item android:state_focused="true" android:drawable="@drawable/focus_button_image" /> <!-- focused -->
<item android:drawable="@drawable/unclicked_button_image"/> <!-- default -->
</selector>