在以前版本的 Gmail 应用中,ActionBar 上有个刷新菜单,点击一下刷新菜单变成一个转圈的刷新标示动画图片。 之前实现该功能的时候都是使用一个类库 RefreshActionItem 来实现的。RefreshActionItem 还支持一些扩展功能,功能比较丰富。
今天无意中又发现一个简单的实现方式。如果您只需要一个刷新的效果,则可以考虑这种方法, 实现方式如下:
1. 首先定义一个 Menu xml 文件:
1
2
3
4
5
6
7
8
9
10
11
|
<?
xml
version
=
"1.0"
encoding
=
"utf-8"
?>
<
item
android:id
=
"@id/menu_refresh"
android:icon
=
"@drawable/icon_refresh"
android:orderInCategory
=
"100"
android:showAsAction
=
"always"
android:title
=
"@string/action_refresh"
/>
</
menu
>
|
2. 然后创建一个代表刷新进度的自定义 ProgressBar 布局文件 actionbar_indeterminate_progress.xml:
1
2
3
4
5
6
7
8
9
10
|
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
private
Menu mOptionsMenu;
@Override
public
boolean
onCreateOptionsMenu(Menu menu) {
mOptionsMenu = menu;
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_content, menu);
return
true
;
}
public
void
setRefreshActionButtonState(
boolean
refreshing) {
if
(mOptionsMenu ==
null
) {
return
;
}
final
MenuItem refreshItem = mOptionsMenu.findItem(R.id.menu_refresh);
if
(refreshItem !=
null
) {
if
(refreshing) {
MenuItemCompat.setActionView(refreshItem, R.layout.actionbar_indeterminate_progress);
}
else
{
MenuItemCompat.setActionView(refreshItem,
null
);
}
}
}
|
这里为了兼容 AppCompat (android 3.0 之前的版本)用了 MenuItemCompat 来设置 ActionView。
现在,根据您的刷新逻辑,只需要调用 setRefreshActionButtonState 函数就可以启用刷新动画了。
这种方式,值得一提的是, 如果你设置了 ActionView,则就是一个自定义 ActionItem,如果在 ActionView 中你不处理 OnClick 事件,则用户点击该菜单是没响应的,这种行为刚好是应用需要的行为。