Reputation: 3578
I'm trying to animate a menu item, while the activity is loading, in my ActionBar (actually ActionBarSherlock). The code I have works the first time the activity is created, but any time the activity is called again, I get a NullReference exception on "loadingItem" because onCreateOptionsMenu
is called after onCreate
. I tried using onPrepareOptionsMenu
but the same thing.
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>
Update:
This ultimately what I'm trying to accomplish. I have a WebView and I want to show a loading icon until the WebView has finished loading:
@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);
}
}
});
}
Upvotes: 1
Views: 6287
Reputation: 22240
onCreateOptionsMenu
will always be called after onCreate
. In fact, onCreate
will always be the first method called when an activity is created.
You should either assign the loadingItem
variable before you use it, or declare it as static so that the reference isn't deleted when the activity is destroyed (which still may happen, in which case I recommend the first option).
Why not set the animation in onCreateOptionsMenu
?
Upvotes: 1