首页 > 系统 > Android > 正文

通用的Android控件抖动效果实现

2019-11-09 17:14:29
字体:
来源:转载
供稿:网友

   这个小程序的功能在实际的开发中会用到,比如:设置Button左右晃动,或者上下的晃动效果,下面就给出示例代码。

首先:要定义一个xml文件,命名为Shake

[html] view plain copy 在CODE上查看代码片<?xml version="1.0" encoding="utf-8"?>  <translate xmlns:android="http://schemas.android.com/apk/res/android"        android:fromXDelta="0"        android:toXDelta="100"        android:duration="1000"        android:interpolator="@anim/cycle_7" />  

接下来再定义一个xml文件,命名为cycle_7

[html] view%20plain copy <?xml version="1.0" encoding="utf-8"?>  <cycleInterpolator xmlns:android="http://schemas.android.com/apk/res/android"        android:cycles="2"          />  

这两个xml文件都要建在,res文件夹下面的anim文件中,如果没有anim文件,可以自己建一个。

然后就是新建一个activity代码如下

[java] view%20plain copy import android.app.Activity;  import android.os.Bundle;  import android.view.View;  import android.view.animation.Animation;  import android.view.animation.AnimationUtils;    public class MainActivity extends Activity {      /** Called when the activity is first created. */                  @Override      public void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.main);      }                  public void go(View v){           Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);//加载动画资源文件          findViewById(R.id.tv).startAnimation(shake); //给组件播放动画效果      }    }  下面给出main.xml

[html] view%20plain copy 派生到我的代码片<?xml version="1.0" encoding="utf-8"?>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"      android:layout_width="fill_parent"      android:layout_height="fill_parent"      android:orientation="vertical"       android:gravity="center_horizontal|center_vertical"      >      <EditText           android:layout_width="fill_parent"      android:layout_height="wrap_content"          android:id="@+id/tv"          android:text="wojiuahiswo"          />            <Button           android:layout_width="fill_parent"      android:layout_height="wrap_content"          android:text="go"          android:onClick="go"          />      </LinearLayout>  

这样就实现了一个edittext控件的抖动效果,这里说明一下cycle_7.xml文件中Android:cycles="2" 这一项是设置抖动的次数的,2为抖动两次。而shake.xml中

android:fromXDelta="0" android:toXDelta="100"

是控制抖动的范围的,上面的代码是在x轴进行抖动,如果把x替换为y就是在y轴进行抖动,当然也可以在x,y轴同时抖动。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表