android开发自定义开关,Android自定义开关样式按钮

概述

在Android开发中尤其是Android TV中,经常需要用到按钮的控件,如何实现一个好看并且带有切换动画的按钮呢,本文就将介绍一种简单的自定义按钮控件。

本文主要涉及到的内容

1.自定义控件的使用

2.动画效果的使用

先给大家看下效果图

8ea65f91f7c6

效果图.gif

一、首先需要编写布局文件,也就是你想要这个按钮的样式是什么样的就通过布局文件来实现。本节实现的是需要两个TextView来显示文字和一个滑动的ImageView实现的滑块。

1.1两个TextView的实现

android:id="@+id/switch_layout"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="@drawable/user_switch_off_bg"

android:gravity="center" >

android:id="@+id/switch_on_title"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentLeft="true"

android:layout_marginLeft="15dp"

android:shadowColor="@color/transparent"

android:textColor="@color/white"

android:textSize="@dimen/size_20" />

android:id="@+id/switch_off_title"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentRight="true"

android:layout_marginRight="15dp"

android:shadowColor="@color/transparent"

android:textColor="@color/white"

android:textSize="@dimen/size_20" />

1.2滑动块的实现

android:id="@+id/switch_flag"

android:layout_width="60dp"

android:layout_height="45dp"

android:layout_centerVertical="true"

android:layout_marginLeft="10dp"

android:src="@drawable/user_switch_btn" />

二、接下来就是要实现一个继承RelativeLayout的类,里面定义了设置按钮文字和滑块滑动的动画。

2.1首先要加载刚才实现的布局

LayoutInflater.from(context).inflate(R.layout.switch_on_off_view_layout, this);

2.2设置按钮文字的实现,也就是将两个TextView设置显示文字

public void setSwitchText(String onText,String OffText){

if(mSwitchOnText == null || mSwitchOffText == null)

return;

mSwitchOnText.setText(onText);

mSwitchOffText.setText(OffText);

}

2.3滑块动画效果的实现

public void switchAnim(boolean show){

float moveToRight = 75f;

float moveToLeft = 0f;

if(show){

mSwitchLayout.setBackgroundResource(R.drawable.user_switch_on_bg);

}else{

moveToRight = 0f;

moveToLeft = 75f;

mSwitchLayout.setBackgroundResource(R.drawable.user_switch_off_bg);

}

ObjectAnimator animator = ObjectAnimator.ofFloat(mSwitchFlagImg, "translationX", moveToLeft, moveToRight);

animator.setDuration(ANIM_DURATION);

animator.start();

}

到此,功能基本上已经实现了,然后就是在代码用如何使用

三、在代码中的使用

3.1在xml中引用自定义好的view

android:id="@+id/disturb_switch"

android:layout_width="130dp"

android:layout_height="fill_parent"

android:layout_marginLeft="10dp"

android:background="@drawable/user_switch_selector" />

然后在代码中和平时使用其他控件一样的方法去使用这个自定义的按钮的控件。

四、结尾

本节是定义的一个比较简单的带有动画效果的按钮的自定义控件,理解了其中的方法后可以实现更加复杂,效果更好的自定义控件。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值