Reputation:
I am using ToolBar
in my app and using menu on it. The menu appears but does not work. I have 4 items in menu, but none of them works. Here's my menu_main.xml
<?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:icon="@drawable/home_icon"
android:id="@+id/home"
android:orderInCategory="100"
android:title="Home"
app:showAsAction="ifRoom" />
<item
android:icon="@drawable/stop"
android:id="@+id/stop"
android:orderInCategory="100"
android:title="Stop"
app:showAsAction="ifRoom" />
<item
android:icon="@drawable/home_icon"
android:id="@+id/refresh"
android:orderInCategory="100"
android:title="Refresh"
app:showAsAction="never" />
<item
android:id="@+id/about"
android:orderInCategory="100"
android:title="About"
app:showAsAction="never" />
</menu>
and here's the code in my java file
public class LoginActivity extends AppCompatActivity {
public String url;
private ProgressBar mProgressBar;
WebView myWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
final String url = "http://softglobe.net/client-projects/rathi-classes/";
// Request window feature action bar
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.inflateMenu(R.menu.menu_main);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.stop:
myWebView.stopLoading();
return true;
case R.id.home:
finish();
Toast.makeText(LoginActivity.this, "Home clicked", Toast.LENGTH_SHORT).show();
return true;
case R.id.refresh:
myWebView.reload();
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
I have made the menu inflate in my java file but still any click is not being handled. Please help me to figure out the solution for this.
Upvotes: 1
Views: 2064
Reputation: 1857
First You don't need to call
toolbar.inflateMenu(R.menu.menu_main);
Second in order to have your toolbar as the actionbar you have to set it as a supportActionBar. So add this lines
setSupportActionBar(toolbar);
Upvotes: 2
Reputation: 1044
As far as I use the toolbar, you have to override the onCreateOptionsMenu(Menu menu)
function. Also, remove the toolbar.onCreateOptionsMenu(menu)
call from the onCreate
method.
As I can see from your code, you also haven't set the toolbar as action bar. You can do that by:
setSupportActionBar(toolbar);
Upvotes: 0