Reputation: 25
I have created a dropdown list in my android action bar with 2 items inside it. I want to be able to add onClick functions to these 2 items so that I can make them open another activity. Below is the xml code where I set up one of the items in the dropdown list:
<item
android:id="@+id/action_home"
android:title="@string/home"
app:showAsAction="never" />
I then have the ActionBar.java class:
public class ActionBar extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_home:
Intent i = new Intent(ActionBar.this, MainActivity.class);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Whenever I click this 'action_home' item in my actionbar nothing happens, but I need it to open my homepage (MainActivity).
I also have the following code in all of my activities java classes in order to make the actionbar appear:
@Override
public boolean onCreateOptionsMenu (Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
Any help would be greatly appreciated!
Upvotes: 1
Views: 166
Reputation: 3329
Try This.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.game_menu, menu);
return true;
}
Click handle here.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.new_game:
// Do your code
return true;
case R.id.help:
// Do your code
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Upvotes: 1