Breaking News

How to change options menu at runtime



In this post, we will change our options menu button at runtime.

When that button has a value to use then it's enabled, by default, it will be disabled.

For example, to change OptionsMenu at runtime, we use the Forward button for WebView. If WebView has a forward history then it will be enabled, otherwise, it will be disabled.

To change OptionsMenu at runtime, we created a new forward button in our menu.xml file. And set enabled as false.
 <?xml version="1.0" encoding="utf-8"?>  
 <menu xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:app="http://schemas.android.com/apk/res-auto">  
  
   <item  
     android:id="@+id/Forward"  
     app:showAsAction="never"  
     android:title="Forward"  
     android:orderInCategory="100"  
     android:enabled="false"  
     />  
  
 </menu>  

Then in your activity  --> onCreateOptionsMenu enable a button when WebView has a forward history.
 @Override  
   public boolean onCreateOptionsMenu(Menu menu) {  
     getMenuInflater().inflate(R.menu.menu_main,menu);  
   
     if(mywebview.canGoForward())  
     {  
       menu.getItem(1).setEnabled(true);  
     }  
   
     return true;  
   }  
   


Then in OnOptionsItemSelected handle action of your forward button.

Don't forget to call invalidateoptionsmenu to call onCreateOptionsMenu at runtime.
 @Override  
   public boolean onOptionsItemSelected(MenuItem item) {  
   
     int id = item.getItemId();  
     invalidateOptionsMenu();  
    
     if(id==R.id.Forward)  
     {  
       if(mywebview.canGoForward())  
       {  
         mywebview.goForward();  
       }  
     }  
     
     return super.onOptionsItemSelected(item);  
   }  


Also call, invalidateoptionsmenu in onPageStarted and OnPageFinished.
 mywebview.setWebViewClient(new WebViewClient()  
     {  
       @Override  
       public void onPageStarted(WebView view, String url, Bitmap favicon) {  
         invalidateOptionsMenu();     
         super.onPageStarted(view, url, favicon);  
       }  
   
       @Override  
       public void onPageFinished(WebView view, String url) {  
          invalidateOptionsMenu();  
         super.onPageFinished(view, url);  
       }  

No comments