首先是定义一个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为

这样就完成一一个按钮颜色的变化,蓝色表示开启,黑色表示关闭。
本文介绍如何使用Android ImageButton实现状态切换效果,包括定义ImageButton控件、设置触摸监听、使用Selector实现不同状态下的图标变化等。
374

被折叠的 条评论
为什么被折叠?



