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

来源:互联网 发布:js prototype 阮一峰 编辑:程序博客网 时间:2024/06/13 16:33

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

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

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


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

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <cycleInterpolator xmlns:android="http://schemas.android.com/apk/res/android"   
  3.      android:cycles="2"     
  4.      />  


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

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

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. import android.app.Activity;  
  2. import android.os.Bundle;  
  3. import android.view.View;  
  4. import android.view.animation.Animation;  
  5. import android.view.animation.AnimationUtils;  
  6.   
  7. public class MainActivity extends Activity {  
  8.     /** Called when the activity is first created. */  
  9.       
  10.       
  11.     @Override  
  12.     public void onCreate(Bundle savedInstanceState) {  
  13.         super.onCreate(savedInstanceState);  
  14.         setContentView(R.layout.main);  
  15.     }  
  16.       
  17.       
  18.     public void go(View v){  
  19.          Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);//加载动画资源文件  
  20.         findViewById(R.id.tv).startAnimation(shake); //给组件播放动画效果  
  21.     }  
  22.   
  23. }  

下面给出main.xml

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical"   
  6.     android:gravity="center_horizontal|center_vertical"  
  7.     >  
  8.     <EditText   
  9.         android:layout_width="fill_parent"  
  10.     android:layout_height="wrap_content"  
  11.         android:id="@+id/tv"  
  12.         android:text="wojiuahiswo"  
  13.         />  
  14.       
  15.     <Button   
  16.         android:layout_width="fill_parent"  
  17.     android:layout_height="wrap_content"  
  18.         android:text="go"  
  19.         android:onClick="go"  
  20.         />  
  21.   
  22.   
  23. </LinearLayout>  

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

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

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

2 0
原创粉丝点击