应用场景:在界面内列表或其他部件下拉刷新时,ActionBar 出现一个转圈的刷新标示动画。
实现方式:可使用开源类库 RefreshActionItem (https://github.com/ManuelPeinado/RefreshActionItem),RefreshActionItem 还支持一些扩展功能,功能比较丰富;
如果只需要实现一个刷新和Loading的效果,则可以使用另一种简便的实现方式:
1. 首先定义一个 Menu xml 文件, share_public.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/refresh_loading"
android:icon="@color/transparent"
android:showAsAction="always"
android:title="刷新"/>
</menu>
2. 然后创建一个代表刷新进度的自定义 ProgressBar 布局文件 actionbar_indeterminate_progress.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="56dp"
android:minWidth="56dp">
<ProgressBar android:layout_width="32dp"
android:layout_height="32dp"
android:layout_gravity="center"
style="?indeterminateProgressStyle" />
</FrameLayout>
注意,为了显示美观,上面的 宽度和高度 不同的版本和屏幕可能需要设置不一样的值,可以在不同的 dimens.xml 中设置
3. 在 Activity 代码中,获取到该 MenuItem 并根据刷新情况来设置 ActionView:
MenuItem mProgressMenu;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.share_public, menu);
mProgressMenu = menu.findItem(R.id.refresh_loading);
return true;
}
public void setLoadingState(boolean refreshing) {
if (mProgressMenu != null) {
if (refreshing) {
mProgressMenu
.setActionView(R.layout.actionbar_indeterminate_progress);
mProgressMenu.setVisible(true);
} else {
mProgressMenu.setVisible(false);
mProgressMenu.setActionView(null);
}
}
}
现在,根据您的刷新逻辑,只需要调用 setRefreshActionButtonState 函数就可以启用刷新动画了。
本项目不在 ActionView 中处理 OnClick 事件,用户点击该菜单是没响应的,采用此种方式,loading状态动画只会在刷新时进行,在刷新结束后隐藏。
注:本帖系在参考地址基础上改造,本项目使用了ActionbarSherlock来兼容3.0以下的版本中的Actionbar;
参考地址使用了AppCompat作兼容,在处理添加ActionView操作上略有不同。
转载于:http://blog.chengyunfeng.com/?p=572