我正在尝试在我的 ActionBar(实际上是 ActionBarSherlock)中为菜单项设置动画,同时加载活动。我的代码在第一次创建活动时工作,但任何时候再次调用活动时,我都会在“loadingItem”上得到一个 NullReference 异常,因为onCreateOptionsMenu
在之后调用onCreate
。我尝试使用onPrepareOptionsMenu
但同样的东西。
public class MyActivity extends SherlockActivity {
private MenuItem loadingItem;
@Override
public void onCreate(final Bundle icicle)
{
final LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final ImageView ivRefresh = (ImageView)inflater.inflate(R.layout.refresh_view, null);
final Animation rotation = AnimationUtils.loadAnimation(this, R.anim.refresh);
ivRefresh.startAnimation(rotation);
loadingItem.setActionView(ivRefresh);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.my_menu, menu);
loadingItem = menu.findItem(R.id.loading);
return super.onCreateOptionsMenu(menu);
}
}
my_menu.xml
<?xml version="1.0" encoding="UTF-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/loading"
android:icon="@drawable/loading"
android:showAsAction="always"
/>
</menu>
更新:
这最终是我想要完成的。我有一个 WebView,我想在 WebView 完成加载之前显示一个加载图标:
@Override
public void onCreate(final Bundle icicle)
{
WebView webView = (WebView)findViewById(R.id.webview);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.loadUrl("http://www.google.com");
webView.setWebViewClient(new WebBrowserClient());
final LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final ImageView ivRefresh = (ImageView)inflater.inflate(R.layout.refresh_view, null);
final Animation rotation = AnimationUtils.loadAnimation(this, R.anim.refresh);
ivRefresh.startAnimation(rotation);
loadingItem.setActionView(ivRefresh);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
if (!isFinishing() && progress == 100 && loadingItem != null && loadingItem.getActionView() != null)
{
loadingItem.getActionView().clearAnimation();
loadingItem.setActionView(null);
}
}
});
}