in an android app , I use menus for an activity
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/logout"
android:title="Logout" />
<item
android:id="#+id/compose"
android:title="Compose" />
<item
android:id="#+id/refresh"
android:title="Refresh" />
</menu>
and in activity :
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.inboxmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.logout:
SharedPreferences settings =getSharedPreferences("CASPreferences", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putString("uid", "");
prefEditor.putString("stdno", "");
prefEditor.putString("firstname", "");
prefEditor.putString("lastname", "");
prefEditor.putString("lastname", "");
prefEditor.commit();
Intent myIntent = new Intent(this, LoginActivity.class);
startActivity(myIntent);
return true;
case R.id.refresh:
Log.e("menu" , "refresh");
//Intent intent=new Intent(this,MainActivity.class);
startActivity(getIntent());
finish();
case R.id.compose:
Log.e("menu" , "compose");
Intent intent1=new Intent(this,ComposeActivity.class);
startActivity(intent1);
default:
return super.onOptionsItemSelected(item);
}
}
but when I click on refresh button , it goes to compose activity ! like as you clicked on compose.
why does this happen?
add break to your switch statement, otherwise your code will continue into the third case
You haven`t added break; for each switch stmt.
Please try and share the result.
Rewrite your switch statement.
switch (item.getItemId()) {
case R.id.logout:
...
return true;
case R.id.refresh:
...
finish();
break; // <- Add this line
case R.id.compose:
...
break; // <- Add this line
default:
return super.onOptionsItemSelected(item);
}
Each case block must be enclosed by break.
The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.
break doesn't required in first case block because flow interrupted by return statement.
Reference: http://download.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Related
I am making an app, where the toolbar has a menu, and within has 2-3 checkboxes.I have code put down for xml and java, and checkbox displays. But nothing gets ticked when i press. Code below
action_bar xml which gets included in main activity :
<item
android:id="#+id/eleaf"
app:actionViewClass="android.widget.CheckBox"
android:checkable="true"
android:checked="false"
android:orderInCategory="5"
app:showAsAction="never"
android:buttonTint="#color/colorAccent"
android:title="E-Leaf"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:onClick="itemClicked"/>
Java for onOptionsItemsSelected :
public boolean onOptionsItemSelected(MenuItem item)
{
boolean checked = item.isChecked();
switch (item.getItemId())
{
case R.id.eleaf:
if(checked){
Toast.makeText(this, "E-Leaf Map shown", Toast.LENGTH_SHORT).show();
item.setChecked(false);
}
break;
case R.id.biomass:
if (checked){
Toast.makeText(this, "Biomass Map shown", Toast.LENGTH_SHORT).show();
item.setChecked(false);
}
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
I had this line in oncreate but not really using it :
CheckBox checkEleaf = (CheckBox) findViewById(R.id.eleaf);
Any suggestions on how to go about this. Thanks
Within each case in your switch you have to return true.
You have this code in your 1st case :
case R.id.eleaf:
if(checked){
Toast.makeText(this, "E-Leaf Map shown", Toast.LENGTH_SHORT).show();
item.setChecked(false);
}
break;
In this you are calling setChecked(false) only when its already check by if(checked) condition.. you should change this code to following code :
case R.id.eleaf:
if (checked) {
Toast.makeText(this, "E-Leaf Map shown", Toast.LENGTH_SHORT).show();
}
item.setChecked(!item.isChecked()); // this will make check,uncheck
break;
Right now I have a couple of buttons that do different things when clicked, but now I want one of them to display a menu when clicked, but I am not sure how to do this.
My code is something like this for the main buttons:
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()) {
case R.id.button1:
//do stuff
break;
case R.id.button2:
//display menu
break;
}
If button2 is pressed, I want to display a list of options and see what menu item the user selects, but how can I do this?
Displaying icon in menu
XML
<item
android:id="#+id/item_1"
android:icon="#drawable/settings"
android:showAsAction="always"
android:title="Add item1" />
You could use a PopupMenu In your onOptionsItemSelected() which will then show a different menu when one of your menu buttons is clicked. Modify this piece of code according to your needs:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.button1:
// DO SOMETHING HERE
break;
case R.id.button2:
// THE R.id.button2 has to be the same as the item that will trigger the popup menu.
View v = findViewById(R.id.button2);
PopupMenu pm = new PopupMenu(LoginActivity.this, v);
pm.getMenuInflater().inflate(R.menu.pm_accounts_item, pm.getMenu());
pm.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getApplicationContext(), String.valueOf(item.getTitle()), Toast.LENGTH_SHORT).show();
switch (item.getItemId()) {
case R.id.menuEdit:
break;
case R.id.menuDetails:
break;
case R.id.menuDelete:
break;
default:
break;
}
return true;
}
}); pm.show();
break;
default:
break;
}
return false;
}
You will notice that a new menu XML has been inflated at this line:
pm.getMenuInflater().inflate(R.menu.pm_accounts_item, pm.getMenu());
You will have to create a second menu XML with the list of options that you need to display when one of the buttons is clicked. This is similar to your current menu XML with the difference being, a different set of options.
IMPORTANT!
Do not forget to include this View v = findViewById(R.id.button2); before the PopupMenu pm..... The PopupMenu requires a View to anchor itself to. But the onOptionsItemSelected() method does not provide this at all. Hence the extra statement.
The above example illustrates the example in an Activity. To use this in a Fragment, change the View v = findViewById(R.id.button2); to View v = getActivity().findViewById(R.id.button2);
This is the final result:
If you are talking about Opening option menu, Then there is a method openOptionMenu() in Activity class.
case R.id.button2:
openOptionsMenu();
break;
If you are talking about opening contextMenu
You have to call openContextMenu() method, But don't forget to add registerForContextMenu(view) and other methods for taking action
This is my Code for the action bar i use.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.icon:
case R.id.Kur:
Intent Doviz = new Intent(MainActivity.this, MainActivity.class);
startActivity(Doviz);
finish();
return true;
case R.id.Hesap:
Intent Hesap = new Intent(MainActivity.this, Genel.class);
startActivity(Hesap);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
I'm trying to make it so when someone clicks the icon at top ( which is in red circle at picture) it should do the same thing as my "Döviz Kuru" Button at action bar. I have 2 problems 1 is i cant seem to make same Intent work for 2 cases in the menu 2nd is R.id.İcon doesn't reach to icon. I also tried home and the name i give to that .png neither worked.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case android.R.id.home:
Intent Doviz = new Intent(MainActivity.this, MainActivity.class);
startActivity(Doviz);
finish();
return true;
case R.id.Kur:
Intent Doviz = new Intent(MainActivity.this, MainActivity.class);
startActivity(Doviz);
finish();
return true;
case R.id.Hesap:
Intent Hesap = new Intent(MainActivity.this, Genel.class);
startActivity(Hesap);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
it gives an error abaut "Duplicate local variable Doviz". When i try to use the same Intent for 2 cases.
the answer for the making 2 cases with same job is done like this.
case android.R.id.home:
case R.id.Kur:
Intent Doviz = new Intent(Genel.this, MainActivity.class);
startActivity(Doviz);
finish();
return true;
To enable Home Icon of Actionbar...
Read This Document For More Info : Navigate Up to Parent Activity
You should Do following...
write these lines in OnCreate() method of your activity..
ActionBar actn = getActionBar();
actn.setHomeButtonEnabled(true); //set home button clickable...
actn.setDisplayHomeAsUpEnabled(true); //add up indicator with home button..
add this to onOptionsItemSelected()..
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case android.R.id.home:
//this calls Home Icon of Actionbar...
//your code..
return true;
default:
return super.onOptionsItemSelected(item);
}
}
for calling same code for both cases You can write cases like below..
switch (item.getItemId()) {
case android.R.id.home:
case R.id.Kur:
//this code runs for both cases..
//your code..
return true;
default:
return super.onOptionsItemSelected(item);
}
if you want to restart your activity....
you should use this code..this will restart current activity..
Intent intent = getIntent();
finish();
startActivity(intent);
How do I change the android actionbar title and icon
If you want to change it in code call
setTitle("My new title");
getActionBar().setIcon(R.drawable.my_icon);
And set the values to whatever you please.
I trying to personalize the Android tutorial about Layout Changes (http://developer.android.com/training/animation/layout.html), but in the code there is this code
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// Navigate "up" the demo structure to the launchpad activity.
// See http://developer.android.com/design/patterns/navigation.html
// for more.
NavUtils.navigateUpTo(this, new Intent(this, MainActivity.class));
return true;
case R.id.action_add_item:
// Hide the "empty" view since there is now at least one item in the
// list.
findViewById(android.R.id.empty).setVisibility(View.GONE);
addItem();
return true;
}
return super.onOptionsItemSelected(item);
}
In my case I don't have a button in the menu, but I woud use an external button. I trying to use this button:
<Button
android:id="#+id/buttonPost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="30dp"
android:layout_toRightOf="#+id/editTextComment"
android:text="Post"
android:onClick="add" />
With the method
public void add(View view) {
findViewById(android.R.id.empty).setVisibility(View.GONE);
addItem();
}
But this solution doesn't work. Any ideas?
onOptionsItemSelected is for an options menu used with onCreateOptionsMenu(Menu menu). Simply move this code to your onClick if you want it to work for the Buttons and switch on the Button id.
public void add(View v) {
switch (v.getId()) {
case R.id.buttonPost:
findViewById(android.R.id.empty).setVisibility(View.GONE);
addItem();
break;
case R.id.another_button_id:
// do something else
break;
}
}
Put an OnClickListener on your button instead:
findViewById(R.id.buttonPost).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// do something here
}
});
I have read the instructions at the android developers page's in order to get the Checkable menu items:
http://developer.android.com/guide/topics/ui/menus.html
this is my xmlmenu:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="all">
<item android:id="#+id/regu"
android:title="#string/Regulatory" />
<item android:id="#+id/warn"
android:title="#string/Warning" />
<item android:id="#+id/temp"
android:title="#string/Temporary" />
<item android:id="#+id/bicy"
android:title="#string/Bicycle" />
</group>
</menu>
And here is my code:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.regu:
if (item.isChecked())
{
item.setChecked(false);
currAvailableOptions++;
}
else if(0 != currAvailableOptions)
{
item.setChecked(true);
currAvailableOptions--;
}
return true;
case R.id.warn:
if (item.isChecked())
{
item.setChecked(false);
currAvailableOptions++;
}
else if(0 != currAvailableOptions)
{
item.setChecked(true);
currAvailableOptions--;
}
return true;
case R.id.temp:
if (item.isChecked())
{
item.setChecked(false);
currAvailableOptions++;
}
else if(0 != currAvailableOptions)
{
item.setChecked(true);
currAvailableOptions--;
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.app_menu, menu);
return true;
}
The problem is when I clicked one item, the menu item disappeared. It wouldn't have to stay visible in order to check other menu items?
Any idea?
Greetings
Checkable items appear only in submenus or context menus.
And with submenu they (Google) means:
Submenu A floating list of menu items that appears when the user
touches a menu item that contains a nested menu.
Since your menu items are not submenu items, it will not work
I know this is not a direct answer to your question but please consider the following code instead of your switch, it might help you find the problem.
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.regu:
case R.id.warn:
case R.id.temp:
if (item.isChecked())
currAvailableOptions++;
else if(currAvailableOptions != 0)
currAvailableOptions--;
item.setChecked(!item.isChecked());
return true;
default:
return super.onOptionsItemSelected(item);
}
}
What is currAvailableOptions? I looked at the article you linked to and there wasn't anything about that in there. It would seem that all you need to do is check:
if (item.isChecked())
item.setChecked(false);
else
item.setChecked(true);
or at least that's what the tutorial says. Perhaps you should give it another read? Hope this helps.
You should probably add break; statements after each case:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item1:
item.setChecked(!item.isChecked());
break;
case R.id.item2:
item.setChecked(!item.isChecked());
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}