Issue
How can an options menu item be accessed from an object outside of the menu itself? I’m trying to set an alpha value for one of the options menu items, but it’s not working for some reason. The commented lines are what I tried.
I’ve seen the following code used before, but it’s not clear on where and how it should be used:
Drawable drawable item.getIcon();
if (drawable ! null) {
drawable.mutate();
drawable.setAlpha(1);
}
Activity class
public class WebviewActivity extends AppCompatActivity {
private static final String TAG WebviewActivity.class.getSimpleName();
WebView myWebView;
ProgressBar myProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_webview);
}
@Override
protected void onStart() {
super.onStart();
setContentView(R.layout.fragment_webview);
String url getIntent().getStringExtra("url");
myWebView findViewById(R.id.web_view);
myWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl(url);
myWebView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
myProgressBar.setProgress(newProgress);
}
});
}
private class WebViewClient extends android.webkit.WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request){
String urlrequest.getUrl().toString();
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
}
public void onBtnBackPressed() {
if (myWebView.canGoBack()){
myWebView.goBack();
} else {
onBackPressed();
}
}
public void onBtnForwardPressed() {
if (myWebView.canGoForward()){
myWebView.goForward();
} else {
// menu.getItem(R.id.action_webbrowser_forward).setEnabled(false);
// menu.getItem(R.id.action_webbrowser_forward).mutate();
// menu.getItem(R.id.action_webbrowser_forward).setAlpha(1);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater getMenuInflater();
inflater.inflate(R.menu.web_browser, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
else if (item.getItemId() R.id.action_webbrowser_back) {
onBtnBackPressed();
} else if (item.getItemId() R.id.action_webbrowser_forward) {
onBtnForwardPressed();
}
return super.onOptionsItemSelected(item);
}
}
Solution
Define in your activity class this variable:
MenuItem action_webbrowser_forward;
In onCreateOptionsMenu()
after the inflation of the menu, write this:
action_webbrowser_forward menu.findItem(R.id.action_webbrowser_forward);
then you can use it anywhere in your class:
action_webbrowser_forward.setEnabled(false);
but mutate
is used for drawables and not menu items, so get the icon of the item by action_webbrowser_forward.getIcon()
and apply mutate to it.
Answered By – forpas