public class MainActivity extends AppCompatActivity {
private final int item_4 = 4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onPrepareOptionsMenu();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.menu_main, menu);
menu.add(Menu.NONE, item_4, Menu.NONE, "Show");
menu.add(Menu.NONE, item_4, Menu.NONE, "Hide");
menu.add("Reset");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item1:
Toast.makeText(this, "You Pressed Settings", Toast.LENGTH_SHORT).show();
return true;
case R.id.item2:
Toast.makeText(this, "You Pressed Create", Toast.LENGTH_SHORT).show();
return true;
case R.id.item3:
Toast.makeText(this, "You Pressed Delete", Toast.LENGTH_SHORT).show();
return true;
case item_4:
Toast.makeText(this, "You Pressed Hide", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem mii = menu.findItem(R.id.item2);
mii.setEnabled(false);
return super.onPrepareOptionsMenu(menu);
}
}
In the above code I have created a menu item list for the app bar and I have created a button in my app and i want some of my items to be disabled after button click but I am not able to do so as I am not gettig how to call onPrepareOptionsMenu() on button click? Can anyone suggest a solution for how to disable the menu items after button click?
I will show short example:
Only one note for this method: don’t forget to clear menu items (menu.clear();) on every method start.
Example:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* Class which shows how to change dynamically options menu items
*/
public class Main extends Activity {
private Button clickBtn;
private boolean isChangedStat = false;
private static final int MENUITEM = Menu.FIRST;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
clickBtn = (Button) findViewById(R.id.click);
clickBtn.setText("Click me");
clickBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(isChangedStat) {
isChangedStat = false;
} else {
isChangedStat = true;
}
}
});
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
if(isChangedStat) {
menu.add(0, MENUITEM, 0, "True");
} else {
menu.add(0, MENUITEM, 0, "False");
}
return super.onPrepareOptionsMenu(menu);
}
}
Reference from:
Android: How to enable/disable option menu item on button click?
Once the activity is created, the onCreateOptionsMenu() method is
called only once, as described above. The system keeps and re-uses the
Menu you define in this method until your activity is destroyed. If
you want to change the Options Menu any time after it's first created,
you must override the onPrepareOptionsMenu() method. This passes you
the Menu object as it currently exists. This is useful if you'd like
to remove, add, disable, or enable menu items depending on the current
state of your application.
you could call the method invalidateOptionsMenu(); in your button's click listener. It will call onPrepareOptionsMenu() again, all your logic to disable could be written here.
Anyway, documents covers all.
Related
I want to open a menu from a OnClickListener
without using the method onCreateOptionsMenu
My code:
toolbar.setNavigationIcon(R.drawable.week); //your icon
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v ) {
}
});
Thanks in advance!
I think you want to show/hide a menu item based on actions from users. To do that you must use onCreateOptionsMenu and whenever you want to show/hide the menu item, then call invalidateOptionsMenu (this method will call onCreateOptionsMenu again).
boolean mShowMenu = false;
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.your_menu, menu);
MenuItem item = menu.findItem(R.id.your_menu_item);
item.setVisible(showMenu);
return true;
}
And in your code, when you want to show menu item.
toolbar.setNavigationIcon(R.drawable.week); //your icon
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v ) {
mShowMenu = true;
invalidateOptionsMenu();
}
});
And give it a try.
You should need to create menu Interface in xml File Like this
<item
android:id="#+id/settings"
android:title="Setting"
app:showAsAction="never" />
<item
android:id="#+id/my_activity"
android:title="My Activity"
app:showAsAction="always"
android:icon="#android:drawable/btn_radio"/>
After that in the Java code of a particular class You need to create the code like this;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.my_activity) {
Intent intent1 = new Intent(this,MyActivity.class);
this.startActivity(intent1);
return true;
}
if (id == R.id.settings) {
Toast.makeText(this, "Setting", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
Hopefully this may resolve your problem
I have a menu and when clicked on a menu, it goes inside another menu.
for example, mainmenu-->click on airport guide --> menu2
but when i am in menu2 and press on the back button, the app is closing instead of going back to mainmenu . i am not able to figure out the problem here. i am new to android development
package com.shashank.sharjahinternationalairport;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
public class MainActivity extends Activity {
ImageButton flightInfoButton;
ImageButton airportGuideButton;
ImageButton visitorInfoButton;
ImageButton saaDcaButton;
ImageButton cargoButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
flightInfoButton = (ImageButton) findViewById(R.id.flightInfo);
airportGuideButton = (ImageButton) findViewById(R.id.airportGuide);
visitorInfoButton = (ImageButton) findViewById(R.id.visitorInfo);
saaDcaButton = (ImageButton) findViewById(R.id.saaDca);
cargoButton = (ImageButton) findViewById(R.id.cargo);
airportGuideButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View V){
setContentView(R.layout.airport_guide);
}
});
visitorInfoButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View V){
setContentView(R.layout.visitor_info);
}
});
saaDcaButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View V){
setContentView(R.layout.saa_dca);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
You are using setContentView, so you are just changing the view layout. When you press the backbutton, the Android calls onBackPressed, which the default implementation is to call finnish() method, that closes the activity.
You can override the onBackPressed method to set the other view.
#Override
public void onBackPressed()
{
//setContentView the previous view
}
Hope it helps!
you can always override the onBackPressed method of Activity, you'll have something like this
public class MainActivity extends Activity {
ImageButton flightInfoButton;
ImageButton airportGuideButton;
ImageButton visitorInfoButton;
ImageButton saaDcaButton;
ImageButton cargoButton;
private enum VIEWS {
VIEW_1, VIEW_2, VIEW_3
};
private VIEWS mSelectedView = VIEWS.VIEW_1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
flightInfoButton = (ImageButton) findViewById(R.id.flightInfo);
airportGuideButton = (ImageButton) findViewById(R.id.airportGuide);
visitorInfoButton = (ImageButton) findViewById(R.id.visitorInfo);
saaDcaButton = (ImageButton) findViewById(R.id.saaDca);
cargoButton = (ImageButton) findViewById(R.id.cargo);
airportGuideButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View V) {
showView1();
}
});
visitorInfoButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View V) {
showView2();
}
});
saaDcaButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View V) {
showView3();
}
});
}
private void showView1() {
setContentView(R.layout.airport_guide);
mSelectedView = VIEWS.VIEW_1;
}
private void showView2() {
setContentView(R.layout.visitor_info);
mSelectedView = VIEWS.VIEW_2;
}
private void showView3() {
setContentView(R.layout.saa_dca);
mSelectedView = VIEWS.VIEW_3;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onBackPressed() {
switch (mSelectedView) {
case VIEW_1:
super.onBackPressed();
break;
case VIEW_2:
showView1();
break;
case VIEW_3:
showView2();
break;
}
}
}
All you is doing that you are changing the Content View of the class MainActivity you need to create sperate classes for your difreent layouts and you can call it by INTENT
This is happennig because you are using only one activity, and on click just changing the content view. Even though this appears like a multi page activity, it is only one screen. Hence onBackPressed() it closes. Yo will have to create different activiies for each of your menu options and start them using Intents on Button Click.
Intent i = new Intent(this, SecondActivity.class);
startActivity(i);
You are using only one activity, if it is many activity mean you can track back to previously loaded activity.
else you must needed only one activity mean please store the layouts in some array, then in the onBackPressed() you can it get LIFO manner
#Override
public void onBackPressed() {
}
I have a TextView. When it is long-clicked, the piece of text over which the long-click was done should be highlighted and a contextual action menu should come up that gives some additional options.
However, if the text is highlighted the contextual action menu is different from what is required. On the other hand, if the desired contextual action menu is shown, the text is not highlighted.
I have been able to zero it down to the return statement in the onLongClick function in the onLongClickListener. Specifically, if the onLongClick function returns true (consumes the click), then the contextual action menu is shown but since the long click was never passed to the text selection tool, it does not get activated. However, if the onLongClick function returns false, the click is passed on to a function that triggers default behavior of copy + paste the text with selection.
The code:
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class HelloTxtView extends Activity {
//private EditText ed;
private TextView ed;
//actionmode callback.
private ActionMode mActionMode;
private ActionMode.Callback mActionModeCallback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello_txt_view);
ed = (TextView) findViewById(R.id.txtview);
ed.setFocusable(true);
ed.setText("Hello World! Let's select some text!!");
initActionModeCallbacks();
ed.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Log.v(this.toString(), "Long click.");
ed.setCursorVisible(true);
Log.v(this.toString(), "Starting actionmodecallback.");
mActionMode = HelloTxtView.this.startActionMode(mActionModeCallback);
v.setSelected(true);
return false;
}
});
}
public void initActionModeCallbacks() {
/*
* This function initializes the callbacks.
*/
mActionModeCallback = new ActionMode.Callback() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
//nothing to do here.
Log.v(this.toString(), "Preparing action mode.");
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
Log.v(this.toString(), "Destroy action mode.");
//mActionModeCallback = null;
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
Log.v(this.toString(), "Creating new action mode menu.");
//inflate a new menu.
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
Log.v(this.toString(), "Done inflating menu.");
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
Log.v(this.toString(), "An item was clicked.");
switch(item.getItemId()) {
case R.id.dictLookup:
Log.v(this.toString(), "Look up dictionary.");
break;
case R.id.readFromHere:
Log.v(this.toString(), "Start reading from here:" + ed.getSelectionStart());
}
return false;
}
};
}
}
My question(s):
1. How do I override the default behavior of the TextView?
2. How do I get text selection with contextual action menu?
if you want to get custom contextual action mode on text selection, then you can do somehing like this
ed = (TextView) findViewById(R.id.txtview);
ed.setText("Hello World! Let's select some text!!");
initActionModeCallbacks();
ed.setTextIsSelectable(true);
ed.setCustomSelectionActionModeCallback(mActionModeCallback);
ed.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Log.v(this.toString(), "Long click.");
ed.setCursorVisible(true);
v.setSelected(true);
return false;
}
});
and in onCreateActionMode(ActionMode mode, Menu menu), if you want to remove standard selection items, you can call
menu.clear();
also note, items in your menu needs to have SHOW_AS_ACTION_ALWAYS flag, because overflow button is not working cause focus change https://stackoverflow.com/a/9883763/2751697
So I have menu items on action bar. on onOptionsItemSelected, I want to change the menu items images.
Here's my code
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.todaySched:{
viewTodaySched();
item.setIcon(R.drawable.calendarselected);
infoLog=(MenuItem)findViewById(R.id.infoLog);
infoLog.setIcon(R.drawable.book);
return true;}
case R.id.infoLog:{
viewInfoLog();
item.setIcon(R.drawable.bookselected);
todaySched=(MenuItem)findViewById(R.id.todaySched);
todaySched.setIcon(R.drawable.calenderselected);
return true;}
default:
return super.onOptionsItemSelected(item);
}
}
But the icon won't change when I clicked it, and I got run time error.
e.g: When I click todaySched icon, It seems like I can't get the infoLog item id.
My LogCat: LogCat
As per you logcat, you getting class cast exception and you have used sharlockactionbar.
so try and check if you have imported the correct MenuItem and Menu which should like this:
import com.actionbarsherlock.view.MenuItem;
and
import com.actionbarsherlock.view.Menu;
instead of
import android.view.MenuItem;
and
import android.view.Menu;
Edit:
Here is how you can change both icons on just a single click:
private Menu menu;
private MenuItem item1, item2;
Boolean original = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.menu, menu);
this.menu = menu;
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.todaySched) {
update();
} else if (id == R.id.infoLog) {
update();
}
return true;
}
private void update() {
item1 = menu.findItem(R.id.todaySched);
item2 = menu.findItem(R.id.infoLog);
if (original) {
item1.setIcon(getResources().getDrawable(
android.R.drawable.ic_menu_search));
item2.setIcon(getResources().getDrawable(
android.R.drawable.ic_menu_report_image));
original = false;
} else if (!original) {
item1.setIcon(getResources().getDrawable(
android.R.drawable.ic_menu_my_calendar));
item2.setIcon(getResources().getDrawable(
android.R.drawable.ic_menu_info_details));
original = true;
}
}
checked and is working. Now use it as per your requirement..
Cheers....
Every time you want to make changes to your items in the Action bar you have to call the function
invalidateOptionsMenu(). Then you override the method public boolean onPrepareOptionsMenu(Menu menu), there you get your menu items and you can set icons, create new actions or remove them. Hope it helps.
Here I tried to make option menu, but menu is not displaying on screen, so please guide me where am I doing mistake...
MenuTest.java
public class MenuTest extends Activity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.more_tab_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.feeds:
break;
case R.id.friends:
break;
case R.id.about:
break;
}
return true;
}
}
And my XML file is more_tab_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/feeds"
android:title="Feeds"/>
<item
android:id="#+id/friends"
android:title="Friends"/>
<item
android:id="#+id/about"
android:title="About"/>
</menu>
Please guide me,
public class MenuTest extends Activity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.more_tab_menu, menu);
// return true so that the menu pop up is opened
return true;
}
}
and don't forget to press the menu button or icon on Emulator or device
please see :==
private int group1Id = 1;
int homeId = Menu.FIRST;
int profileId = Menu.FIRST +1;
int searchId = Menu.FIRST +2;
int dealsId = Menu.FIRST +3;
int helpId = Menu.FIRST +4;
int contactusId = Menu.FIRST +5;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(group1Id, homeId, homeId, "").setIcon(R.drawable.home_menu);
menu.add(group1Id, profileId, profileId, "").setIcon(R.drawable.profile_menu);
menu.add(group1Id, searchId, searchId, "").setIcon(R.drawable.search_menu);
menu.add(group1Id, dealsId, dealsId, "").setIcon(R.drawable.deals_menu);
menu.add(group1Id, helpId, helpId, "").setIcon(R.drawable.help_menu);
menu.add(group1Id, contactusId, contactusId, "").setIcon(R.drawable.contactus_menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1:
// write your code here
Toast msg = Toast.makeText(MainHomeScreen.this, "Menu 1", Toast.LENGTH_LONG);
msg.show();
return true;
case 2:
// write your code here
return true;
case 3:
// write your code here
return true;
case 4:
// write your code here
return true;
case 5:
// write your code here
return true;
case 6:
// write your code here
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Change your onCreateOptionsMenu method to return true. To quote the docs:
You must return true for the menu to be displayed; if you return false it will not be shown.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(this).inflate(R.menu.folderview_options, menu);
return (super.onCreateOptionsMenu(menu));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.locationListRefreshLocations) {
Cursor temp = helper.getEmployee(active_employeeId);
String[] matches = new String[1];
if (temp.moveToFirst()) {
matches[0] = helper.getEmployerID(temp);
}
temp.close();
startRosterReceiveBackgroundTask(matches);
} else if (item.getItemId()==R.id.locationListPrefs) {
startActivity(new Intent(this, PreferencesUnlockScreen.class));
return true;
}
return super.onOptionsItemSelected(item);
}
you can create options menu like below:
Menu XML code:
<?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/Menu_AboutUs"
android:icon="#drawable/ic_about_us_over_black"
android:title="About US"/>
<item
android:id="#+id/Menu_LogOutMenu"
android:icon="#drawable/ic_arrow_forward_black"
android:title="Logout"/>
</menu>
How you can get the menu from MENU XML(Convert menu XML to java):
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my_options_menu,menu);
return super.onCreateOptionsMenu(menu);
}
How to get Selected Item from Menu:
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.Menu_AboutUs:
//About US
break;
case R.id.Menu_LogOutMenu:
//Do Logout
break;
}
return super.onOptionsItemSelected(item);
}
import android.app.Activity;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
public class AndroidWalkthroughApp2 extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// show menu when menu button is pressed
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// display a message when a button was pressed
String message = "";
if (item.getItemId() == R.id.option1) {
message = "You selected option 1!";
}
else if (item.getItemId() == R.id.option2) {
message = "You selected option 2!";
}
else {
message = "Why would you select that!?";
}
// show message via toast
Toast toast = Toast.makeText(this, message, Toast.LENGTH_LONG);
toast.show();
return true;
}
}
Replace return super.onCreateOptionsMenu(menu); with return true; in your onCreateOptionsMenu method
This will help
And you should also have the onCreate method in your activity
The previous answers have covered the traditional menu used in android. Their is another option you can use if you are looking for an alternative
https://github.com/AnshulBansal/Android-Pulley-Menu
Pulley menu is an alternate to the traditional Menu which allows user to select any option for an activity intuitively. The menu is revealed by dragging the screen downwards and in that gesture user can also select any of the options.
Android UI programming is a little bit tricky. To enable the Options menu, in addition to the code you wrote, we also need to call setHasOptionsMenu(true) in your overriden method OnCreate().
Hope this will help you out.
IF your Device is running Android v.4.1.2 or before,
the menu is not displayed in the action-bar.
But it can be accessed through the Menu-(hardware)-Button.
Good Day
I was checked
And if You choose Empty Activity
You Don't have build in Menu functions
For Build in You must choose Basic Activity
In this way You Activity will run onCreateOptionsMenu
Or if You work in Empty Activity from start
Chenge in styles.xml the