android switch的使用方法,Android UI控件Switch的使用方法

在Android中偶尔会用到开关,Switch就是一个简单易使用的不错的控件。

首先,在布局中添加上Switch控件:

android:id="@+id/s_v"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:switchMinWidth="20dp"

android:textOn="on"

android:textOff="off"

android:thumb="@drawable/thumb"

android:track="@drawable/track" />

以下是该控件的常用属性:

textOn:控件打开时显示的文字

textOff:控件关闭时显示的文字

thumb:控件开关的图片

track:控件开关的轨迹图片

typeface:设置字体类型

switchMinWidth:开关最小宽度

switchPadding:设置开关 与文字的空白距离

switchTextAppearance:设置文本的风格

checked:设置初始选中状态

splitTrack:是否设置一个间隙,让滑块与底部图片分隔(API 21及以上)

showText:设置是否显示开关上的文字(API 21及以上)

我们一般不会用该控件原本的样式,那么我们就需要自己修改样式了:

gray_thumb.xml:

android:shape="rectangle" >

android:endColor="#ffffff"

android:startColor="#ffffff" />

android:color="#9e9e9e"/>

green_thumb.xml:

android:shape="rectangle" >

android:endColor="#ffffff"

android:startColor="#ffffff" />

android:color="#33da33"/>

gray_track.xml:

android:shape="rectangle" >

android:endColor="#9e9e9e"

android:startColor="#9e9e9e" />

green_track.xml:

android:endColor="#33da33"

android:startColor="#33da33" />

thumb.xml:

track.xml:

在styles.xml中添加如下style:

#33da33

#9b9b9b

最后,只需要将控件实例化出来进行相应操作就可以了:

MainActivity.class:

public class MainActivity extends Activity{

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

final Switch aSwitch = (Switch) findViewById(R.id.s_v);

aSwitch.setChecked(false);

aSwitch.setSwitchTextAppearance(MainActivity.this,R.style.x1);

aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

@Override

public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

//控制开关字体颜色

if (b) {

aSwitch.setSwitchTextAppearance(MainActivity.this,R.style.s_true);

}else {

aSwitch.setSwitchTextAppearance(MainActivity.this,R.style.x1);

}

}

});

}

}

最终效果如下图:

e5e965a4fa868f13015fa7c88e0eef87.png

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值