做一个Android按钮更改背景的点击通过XML做一个、按钮、背景、XML

2023-09-12 00:31:48 作者:总萌大人

有没有一种方法来指定一个替代的背景图像/颜色的XML文件中的一个按钮,将被应用于的onClick ,或做我必须做 Button.setBackground() onClickListener

Is there a way to specify an alternative background image/color for a Button in the XML file that is going to be applied onClick, or do I have to do a Button.setBackground() in the onClickListener?

推荐答案

要使用code修改图片

To change image by using code

public void onClick(View v) {
   if(v == ButtonName) {
     ButtonName.setImageResource(R.drawable.ImageName);
   }
}

或者,使用XML文件:

Or, using an XML file:

<?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/login_selected" /> <!-- pressed -->
  <item android:state_focused="true"
   android:drawable="@drawable/login_mouse_over" /> <!-- focused -->
  <item android:drawable="@drawable/login" /> <!-- default -->
</selector>

的OnClick ,只需添加这code:

In OnClick, just add this code:

ButtonName.setBackgroundDrawable(getResources().getDrawable(R.drawable.ImageName));