实现按钮的左右的移动的效果

本文介绍如何使用Android ImageButton实现状态切换效果,包括定义ImageButton控件、设置触摸监听、使用Selector实现不同状态下的图标变化等。

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

首先是定义一个imageButton的控件并让控件能够监听触摸时间
decodingMode= (ImageButton) findViewById(R.id.decodingMode);
decodingMode.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        if(decodingMode.isSelected()){
            decodingMode.setSelected(false);
        }else {
            decodingMode.setSelected(true);
        }
    }
});
在xml布局文件里对imagebutton进行定义
<ImageButton
    android:id="@+id/decodingMode"
    android:layout_width="@dimen/dp50"
    android:layout_height="@dimen/dp24""
    android:background="@color/transparent"
    android:clickable="true"
    android:scaleType="fitCenter"
    android:src="@drawable/icon_switch_check" />
/>

android:background="@color/transparent"是让图片的背景是透明的,其中transparent的定义是下面的定义

<color name="transparent">#00000000</color>
其中最为关键的是android:src="@drawable/icon_switch_check",这里的icon_switch_check并不是一个图片,而是定义的一个xml文件,放在drawable里面的。具体的定义如下:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/icon_open" android:state_selected="true"/>
    <item android:drawable="@drawable/icon_open" android:state_checked="true"/>
    <item android:drawable="@drawable/icon_off"/>
</selector>
这里定义了一个selector,里面的每个item是定义的一个属性的值。
其中里面的两个图片其中之一icon_open
另一个为icon_off

这样就完成一一个按钮颜色的变化,蓝色表示开启,黑色表示关闭。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值