在ActionBar添加刷新Loading狀態
應用場景:在界麵內列表或其他部件下拉刷新時,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="https://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="https://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);
- }
- }
- }
本項目不在 ActionView 中處理 OnClick 事件,用戶點擊該菜單是沒響應的,采用此種方式,loading狀態動畫隻會在刷新時進行,在刷新結束後隱藏。
注:本帖係在參考地址基礎上改造,本項目使用了ActionbarSherlock來兼容3.0以下的版本中的Actionbar;
參考地址使用了AppCompat作兼容,在處理添加ActionView操作上略有不同。
參考地址Read more: https://blog.chengyunfeng.com/?p=572
最後更新:2017-04-03 12:55:33