安卓自定义控件xml背景切换

由于工作需要,需要给自定义button弄几种自定义背景,在不同情况下切换到不同背景。在网上查资料时,发现基本所有的资料都集中“pressed”、“focused”和一般情况下的3中不同背景切换。加入我们在除了按下、获得焦点等情况下还想改变控件背景可以这样做:

1.自定义背景,也就是shape,我这里写的是一个带渐变色的圆角矩形按钮。将这个文件放在drawable文件夹中,方便引用。具体shape文件写法请自行网上搜索

bg_shape1.xml:

<?xml version="1.0" encoding="utf-8"?>  
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">  
   <item>  
      <shape android:shape="rectangle">   
         <solid android:color="#FFEC7600" />  
         <corners  
            android:topLeftRadius="35dip"  
            android:topRightRadius="35dip"  
            android:bottomLeftRadius="35dip"  
            android:bottomRightRadius="35dip" />  
      </shape>  
   </item>  
   <item android:top="1px" android:bottom="1px" android:left="1px" android:right="1px">  
     <shape>  
        <gradient   
            android:startColor="#FF00FF00" android:endColor="#FFC1FFC1"   
            android:type="linear" android:angle="90"  
            android:centerX="0.5" android:centerY="0.5" />  
        <corners  
            android:topLeftRadius="35dip"  
            android:topRightRadius="35dip"  
            android:bottomLeftRadius="35dip"  
            android:bottomRightRadius="35dip" />  
      </shape>  
   </item>    
</layer-list> 

bg_shape2、bg_shape3跟bg_shape1类似,只是渐变颜色不同,这里不再贴上来。

2.在java程序中引用刚刚写的xml文件,然后根据情况动态改变背景!!!我搞了半天才搞懂是这样引用的。

如果是在布局文件中给button或者其他控件加上自定义背景比较简单,直接用

android:background="@drawable/xxxx"
来引用,然而这样只是静态的。假如我们需要在情况一的时候用bg_shape1,在情况二的时候用bg_shape2,在情况三的时候用bg_shape3。我们就需要在java程序中动态改变控件的背景。程序如下:

if(state == 1){
<span style="white-space:pre">	</span>Drawable pilebutton_green = this.getResources().getDrawable(0x7f02002f);
	this.setBackgroundDrawable(pilebutton_green);
}
else if(state == 2){
	Drawable pilebutton_blue = this.getResources().getDrawable(0x7f020031);
	this.setBackgroundDrawable(pilebutton_blue);
}
else if(state == 3){
	Drawable pilebutton_red = this.getResources().getDrawable(0x7f020030);
        this.setBackgroundDrawable(pilebutton_red);
}
setBackgroundDrawable参数智能是Drawable对象,所以要先定义一个Drawable对象引用我们刚刚写的drawable中的bg_shapeX。其中getDrawable的参数是十六进制数,这个数我们可以在R.java的drawable类中找到:

public static final int bg_shape1=0x7f02002f;
public static final int bg_shape2=0x7f020030;
public static final int bg_shape3=0x7f020031;



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值