android 改变背景图片的两种方法

1.利用drawable XML

在res/drawable下创建文件,如:myselect.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
       <item android:state_focused="true"
             android:drawable="@drawable/buttom_focused"
               />
    <item android:state_checked="true"
          android:drawable="@drawable/buttom_click"/>
    <item android:drawable="@drawable/buttom_normal"/>
</selector>


在layout/main.xml中声明:

 <ImageButton
            android:id="@+id/click"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/sure"
            android:src="@drawable/myselect"
            android:onClick="isClicked"/>

如果要关注它的点击事件,在main.xml对于的Activity中可以这样调用:

  public void isClicked(View view){
        //todo
    }
用这种方法要特别注意item 的顺序,有点像if/esleif的关系,就是说一旦第一个item触发了就不会判断下一个了。


2.在代码中改变背景图片

  boolean notice_btn_flag = true;
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.fun_set_notice_btn:

            if(notice_btn_flag){
                Resources resources = getApplicationContext().getResources();
                Drawable btnDrawable = resources.getDrawable(R.drawable.notice_btn_b);
                notice_btn.setBackgroundDrawable(btnDrawable);
                notice_btn_flag = false;
            }else {
                Resources resources = getApplicationContext().getResources();
                Drawable btnDrawable = resources.getDrawable(R.drawable.notice_btn_a);
                notice_btn.setBackgroundDrawable(btnDrawable);
                notice_btn_flag = true;
            }
        }
    }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值