使用Android动画实现组件抖动
jopen
10年前
其原理很简单,就是使用动画让组件来回摆动,代码如下:
MainActivity:
package com.home.animwindow; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; public class MainActivity extends Activity { private EditText edit; private Button btn; private ImageView image; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edit = (EditText) findViewById(R.id.edit); image = (ImageView) findViewById(R.id.main_iv); btn = (Button) findViewById(R.id.btn); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Animation animation = AnimationUtils.loadAnimation( MainActivity.this, R.anim.myanim); edit.startAnimation(animation); image.startAnimation(animation); } }); } }
布局:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <EditText android:id="@+id/edit" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="100dp" android:text="点击按钮、此窗口抖动" /> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="按钮" /> <ImageView android:id="@+id/main_iv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" /> </LinearLayout>
动画myanim:
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@anim/cycle" > <translate android:duration="300" android:fromXDelta="0" android:fromYDelta="0" android:toXDelta="-10" android:toYDelta="-10" /> <translate android:duration="300" android:fromXDelta="0" android:fromYDelta="0" android:startOffset="300" android:toXDelta="10" android:toYDelta="-10" /> <translate android:duration="300" android:fromXDelta="0" android:fromYDelta="0" android:startOffset="600" android:toXDelta="-10" android:toYDelta="10" /> <translate android:duration="300" android:fromXDelta="0" android:fromYDelta="0" android:startOffset="900" android:toXDelta="10" android:toYDelta="10" /> </set>
cycle: