当前位置: 代码迷 >> Android >> android按钮背景颜色修改解决办法
  详细解决方案

android按钮背景颜色修改解决办法

热度:85   发布时间:2016-04-28 05:49:32.0
android按钮背景颜色修改
总的来说,现在的android的按钮改变都是在点击触发焦点时改变其背景颜色,当失去焦点的时候变回原来的背景颜色,但是现在需求是,在点击按钮时,这个按钮始终为点击后的颜色,当点击另外的按钮或者别的按钮时,才变回原来的颜色,就是不能使用图片的
<selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="true"
           android:drawable="@drawable/bingrenyilan_click" /> <!-- pressed -->
     <item android:state_focused="true"
           android:drawable="@drawable/bingrenyilan" /> <!-- focused -->
     <item android:drawable="@drawable/bingrenyilan" /> <!-- default -->
 </selector>
因为这样只会实现前面失去焦点的背景颜色

现在解决的是在activity里面使用setBackgroundResource直接改背景颜色
btn_tizheng.setBackgroundResource(R.drawable.btn_tizheng_down);
btn_yizhu.setBackgroundResource(R.drawable.btn_yizhu);
btn_jiancha.setBackgroundResource(R.drawable.btn_jiancha);
btn_jianyan.setBackgroundResource(R.drawable.btn_jianyan);
btn_bingli.setBackgroundResource(R.drawable.btn_bingli);


请问有大神有更好的方法么,因为按钮超过100个的话,需要多写至少2000行以上代码
------解决方案--------------------
你要在.xml文件里面加一个android:state_pressed="false"

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_pressed="false" android:drawable="@drawable/默认图片" />
   <item android:state_pressed="true"
   android:drawable="@drawable/bingrenyilan_click" /> <!-- pressed -->
   <item android:state_focused="true"
   android:drawable="@drawable/bingrenyilan" /> <!-- focused -->
   <item android:drawable="@drawable/默认图片" /> <!-- default -->
  </selector>
  相关解决方案