自定义可动态变化布局

来源:互联网 发布:昌德讯程控交换机编程 编辑:程序博客网 时间:2024/05/04 03:02

浏览网页的时候,发现有些页面鼠标经过但未点击时,文字或图像会移动变化。这个时候,就想在android上也实现类似效果,就自定义了一个LinearLayout,最后效果是酱紫。

手指未碰到屏幕时


手指触碰时,未点击,是这样


或这样


这里每个item用到了自定义的布局。

首先重写onTouchEvent(MotionEvent event)。

@SuppressLint("NewApi") @Overridepublic boolean onTouchEvent(MotionEvent event) {// TODO Auto-generated method stubint action = event.getAction();switch (action) {case MotionEvent.ACTION_DOWN:ToRightAnimation();//右移动画return true;case MotionEvent.ACTION_UP:ToLeftAnimation();<span style="font-family: Arial, Helvetica, sans-serif;">//左移动画</span>break;case MotionEvent.ACTION_CANCEL:ToLeftAnimation();//左移动画break;default:break;}return super.onTouchEvent(event);}
这里说明两点,首先ACTION_DOWN,这里要返回 true,接下来的Touch事件才会被执行。至于左移动画要在 ACTION_UP和ACTION_CANCEL都写一遍,是因为在测试时,我发现前者在手指移动出布局范围时,不会触发。而后者,在点一下后,不会触发。所以要写两遍。

至于动画,就是两个属性动画,就是f对透明度和X轴位移进行操作

@SuppressLint("NewApi")private void ToLeftAnimation() {ObjectAnimator animator1 = ObjectAnimator.ofFloat(this,"translationX" , 300F, 0F);ObjectAnimator animator2 = ObjectAnimator.ofFloat(this,"alpha" , 0.7F, 1F);AnimatorSet set = new AnimatorSet();set.play(animator1).with(animator2);set.setDuration(300);set.start();}@SuppressLint("NewApi") private void ToRightAnimation() {ObjectAnimator animator1 = ObjectAnimator.ofFloat(this,"translationX" , 0F, 300F);ObjectAnimator animator2 = ObjectAnimator.ofFloat(this,"alpha" , 1F, 0.7F);AnimatorSet set = new AnimatorSet();set.play(animator1).with(animator2);set.setDuration(300);set.start();}


源码地址



0 0
原创粉丝点击