我们要实现的就是actionbar中刷新的图标,点击之后进行刷新,刷新完成后又回到原先的图标;
首先创建一个耗时任务:
class FakeTask extends AsyncTask<Void,Void,Void>{ @Override protected Void doInBackground(Void... params) { try { Thread.sleep(2000); } catch (InterruptedException e) { } return null; } @Override protected void onPreExecute() { super.onPreExecute(); showLoadingIndicator(true); } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); showLoadingIndicator(false); } }
public void showLoadingIndicator(boolean show){ if(show){ refreshItem.setEnabled(false); refreshItem.setActionView(R.layout.progress); }else { refreshItem.setActionView(null); refreshItem.setEnabled(true); } }
public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if(item==refreshItem){ new FakeTask().execute(); return true; } return super.onOptionsItemSelected(item); }
布局也只有两个文件而已:
首先是progressbar的布局
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" style="@android:style/Widget.ActionButton" android:layout_width="match_parent" android:layout_height="match_parent"> <ProgressBar android:layout_width="32dp" android:layout_height="32dp" style="?android:attr/indeterminateProgressStyle" android:layout_gravity="center"/> </FrameLayout>再者是menu中的图片
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity"> <item android:id="@+id/menu_refresh" android:title="@string/refresh" app:showAsAction="always" android:icon="@drawable/ic_action_refresh"/> </menu>这样的话 点击就可以实现图片与progresbar的交替出现
0.0