我的ActionBar
中有一个菜单项启动了AsyncTask
,当任务正在运行时,我有一个动画菜单项来显示进度。我也在ListView
的每个选项上刷新动画,因为菜单项会根据点击的项目而改变。除了我检查AsyncTask
是否正在运行,onCreateOptionsMenu
并重新启动动画(因为重绘菜单时动画停止),我已经完成了所有工作。不确定是否有更好的方法来做到这一点。
这是我必须检查AsyncTask
是否正在运行的代码并重新启动一个菜单项的动画:
注意:代码中的其他地方我正在使用它来重置菜单,如果重要的话:
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB)
activity.invalidateOptionsMenu();
public class MyFragment extends SherlockListFragment
{
private MenuItem refreshItem;
private AsyncTask<Void, String, Void> fi;
private MenuItem refreshItem;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedState) {
super.onActivityCreated(savedState);
fi = new FetchItems(activity, null);
fi.execute(); //this actually happen when the menu item is selected but I put here for this question
}
@Override
public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
inflater.inflate(R.menu.main_menu, menu);
if (fi != null && fi.getStatus() == AsyncTask.Status.RUNNING)
{
if (refreshItem != null && refreshItem.getActionView() != null)
{
refreshItem.getActionView().clearAnimation();
refreshItem.setActionView(null);
this.StartAnimation();
}
}
else
refreshItem = menu.findItem(R.id.filter);
super.onCreateOptionsMenu(menu, inflater);
}
private class FetchItems extends AsyncTask<Void, String, Void>
{
@Override
protected void onPreExecute()
{
StartAnimation();
}
protected void onPostExecute(final Void unused)
{
if (refreshItem != null && refreshItem.getActionView() != null)
{
refreshItem.getActionView().clearAnimation();
refreshItem.setActionView(null);
}
}
}
private void StartAnimation() {
final LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final ImageView ivRefresh = (ImageView)inflater.inflate(R.layout.refresh_view, null);
final Animation rotation = AnimationUtils.loadAnimation(getActivity(), R.anim.refresh);
ivRefresh.startAnimation(rotation);
refreshItem.setActionView(ivRefresh);
}
}
refresh.xml
<rotate
xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="infinite"
android:interpolator="@android:anim/linear_interpolator"
android:duration="1000"
/>
答案 0 :(得分:0)
想出来。我创建了一个名为StopAnimation的函数:
private void StopAnimation()
{
if (refreshItem != null && refreshItem.getActionView() != null)
{
refreshItem.getActionView().clearAnimation();
refreshItem.setActionView(null);
}
}
然后在onCreateOptionsMenu
我有这段代码:
@Override
public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
inflater.inflate(R.menu.main_menu, menu);
StopAnimation();
refreshItem = menu.findItem(R.id.filter);
if (fi != null && fi.getStatus() == AsyncTask.Status.RUNNING)
this.StartAnimation();
super.onCreateOptionsMenu(menu, inflater);
}