两种button点击后改变颜色的方法selectot和重写

本文介绍了如何在Android中创建自定义按钮,并实现不同状态下的背景变化效果。通过XML选择器资源文件设置按钮的正常、聚焦及按下状态背景,同时提供了一个自定义按钮类OnPressButton的具体实现,用以根据不同状态改变按钮显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.

mybutton_background.xml

<?xml version="1.0" encoding="utf-8"?>
<selector android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_pressed="false"
android:drawable="@drawable/button_background_focus" />
<item android:state_focused="true" android:state_pressed="true"
android:drawable="@drawable/button_background_pressed" />
<item android:state_focused="false" android:state_pressed="true"
android:drawable="@drawable/button_background_pressed" />
<item drawable="@drawable/button_background_normal">
</selector>
android:background="@drawable/mybutton_background"

 

2.

public class OnPressButton extends Button{

public OnPressButton(Context context) {
super(context);
}

public OnPressButton(Context context, AttributeSet attrs){
super(context, attrs);
}

@Override
protected void onDraw(Canvas canvas) {
//sets the button image based on whether the button in its pressed state
setBackgroundDrawable(getResources().getDrawable(isPressed()?R.drawable.btn_on : R.drawable.btn_off));
super.onDraw(canvas);
}

}

 

<view
class="com.mycompany.android.ui.OnPressButton"
android:background="@android:color/transparent"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="My Button" />

 

这句话要注意android:background="@android:color/transparent"

也可以查看http://code.google.com/android/toolbox/custom-components.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值