您的位置:首页 > 移动开发 > Android开发

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

2017-02-07 10:22 387 查看
   这个小程序的功能在实际的开发中会用到,比如:设置Button左右晃动,或者上下的晃动效果,下面就给出示例代码。首先:要定义一个xml文件,命名为Shake[html] view plain copy 



<?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 plain 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 plain 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 plain 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轴同时抖动。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐