通过 XML 单击时使 Android 按钮更改背景 [英] Make an Android button change background on click through XML

查看:31
本文介绍了通过 XML 单击时使 Android 按钮更改背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法为要应用的 XML 文件中的按钮指定替代背景图像/颜色onClick,或者我必须做一个 Button.setBackgroundonClickListener?

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?

推荐答案

使用代码更改图像:

public void onClick(View v) {
   if(v.id == R.id.button_id) {
     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中,添加如下代码:

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

这篇关于通过 XML 单击时使 Android 按钮更改背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆