背景 本着用户的动作反馈原则,给刷新按钮添加旋转动画。
实现 思路是给原来的按钮上面覆盖一层view来承担动画效果,点击按钮时,覆盖的view显示并旋转,此时按钮被覆盖处于不可点击状态;当动画完成时隐藏覆盖的view,按钮又可以被点击了。需要计算动画时间来及时把动画停掉,我采用postdelay解决。
res/menu/main.xml 1 2 3 4 5 6 7 8 9 <menu xmlns:android ="http://schemas.android.com/apk/res/android" > <item android:id ="@+id/refresh" android:icon ="@drawable/ic_action_refresh" android:showAsAction ="always" > </item > </menu >
res/layout/action_view.xml 1 2 3 4 5 6 7 8 9 10 <? xml version="1.0" encoding="utf-8" ?> <ImageView xmlns:android ="http://schemas.android.com/apk/res/android" android:layout_width ="wrap_content" android:layout_height ="wrap_content" android:layout_gravity ="center" android:minHeight ="24dp" android:minWidth ="24dp" android:paddingEnd ="12dp" android:paddingStart ="12dp" android:scaleType ="centerInside" />
res/anim/refresh.xml 设置一秒绕中心旋转720度的动画,这样动画重复次数取1,不用重复
1 2 3 4 5 6 7 8 <? xml version="1.0" encoding="utf-8" ?> <rotate xmlns:android ="http://schemas.android.com/apk/res/android" android:duration ="1000" android:fromDegrees ="0" android:interpolator ="@android:anim/linear_interpolator" android:pivotX ="50%" android:pivotY ="50%" android:toDegrees ="720" />
MainActivity.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 public class MainActivity extends Activity { protected MenuItem refreshItem; @Override protected void onCreate (Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu (Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true ; } @Override public boolean onOptionsItemSelected (MenuItem item) { switch (item.getItemId()) { case R.id.refresh: showRefreshAnimation(item); return true ; default : return super .onOptionsItemSelected(item); } } @SuppressLint ("NewApi" ) private void showRefreshAnimation (MenuItem item) { hideRefreshAnimation(); refreshItem = item; ImageView refreshActionView = (ImageView) getLayoutInflater().inflate(R.layout.action_view, null ); refreshActionView.setImageResource(R.drawable.ic_autorenew_white_24dp); refreshItem.setActionView(refreshActionView); Animation animation = AnimationUtils.loadAnimation(this , R.anim.refresh); animation.setRepeatMode(Animation.RESTART); animation.setRepeatCount(1 ); refreshActionView.startAnimation(animation); new Handler().postDelayed(new Runnable() { @Override public void run () { hideRefreshAnimation(); } }, 1000 ); } @SuppressLint ("NewApi" ) private void hideRefreshAnimation () { if (refreshItem != null ) { View view = refreshItem.getActionView(); if (view != null ) { view.clearAnimation(); refreshItem.setActionView(null ); } } } }
在项目中的应用
Prev: 【Android TimeCat】 原地归并排序
Next: 【Android TimeCat】 MVP架构演进