组合已有控件
在已有控件的基础上,修改它的样式或者组合在一起,增加动画,来实现自己想要的效果。
效果图
原理解析
1.先实现应该改有的布局
详细代码,如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--android:background="@android:color/transparent"-->
<RelativeLayout
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerInParent="true"
android:background="@color/green">
<ImageButton
android:id="@+id/iv_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="@null"
android:src="@mipmap/back" />
</RelativeLayout>
</RelativeLayout>
2.给控件添加响应事件
详细代码如下:
iv_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AnimationUtil.rotationRightHand(iv_button);
new Thread(new Runnable() {//为了体现效果,延迟350毫秒显示,增加了一个线程
@Override
public void run() {
try {
Thread.sleep(350);
handler.sendEmptyMessage(0);//在线程中不能直接修改控件背景,所以启用了handler
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
});
3.给控件添加逻辑和动画
逻辑代码如下:handler中修改控件背景
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
AnimationUtil.rotationRight(iv_button);
if (isBackKey) { //如果是返回键,点击之后转变成菜单键
isBackKey = false;
iv_button.setImageDrawable(getResources().getDrawable(R.mipmap.menu));
} else {//否者如果是菜单键,点击之后转变成返回键
isBackKey = true;
iv_button.setImageDrawable(getResources().getDrawable(R.mipmap.back));
}
}
};
动画(使用的补间动画)代码如下:
补间动画属性有:
AnimationSet 动画集;AlphaAnimation 渐变透明度;RotateAnimation 画面旋转;ScaleAnimation 渐变尺寸缩放;TranslateAnimation 位置移动。
public static void rotationRightHand(ImageButton iv_button) {
AnimationSet animationSet = new AnimationSet(true);
RotateAnimation rota = new RotateAnimation( //旋转画面
0f, 120f, //从0度到120度顺时针旋转
Animation.RELATIVE_TO_SELF, 0.5f,//相对于自己x轴旋转值也就是中心
Animation.RELATIVE_TO_SELF, 0.5f); //相对于y轴旋转值
rota.setDuration(350);
ScaleAnimation scale = new ScaleAnimation( //渐变 -尺寸缩放
1f,1f, //动画起始、结束时X坐标上的伸缩尺寸
1f,1f, //动画起始、结束时Y坐标上的伸缩尺寸
Animation.RELATIVE_TO_SELF, 0.5f,//相对于x轴旋转值
Animation.RELATIVE_TO_SELF, 0.5f);
animationSet.addAnimation(rota);
animationSet.addAnimation(scale);
iv_button.startAnimation(animationSet);
}