open a menu from OnClickListener - android

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

Related

Changing options menu icon

Lets say I have a options menu like below:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_home_page, menu);
final MenuItem myActionMenuItem = menu.findItem(R.id.action_search);
mSearchView = (SearchView) myActionMenuItem.getActionView();
mSearchView.setQueryHint("Enter text to search(min. 3 chars)...");
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(final String searchQuery) {
if (!mSearchView.isIconified()) {
mSearchView.setIconified(true);
}
mSearchView.setQuery(searchQuery, false);
return false;
}
#Override
public boolean onQueryTextChange(String s) {
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
saveState();
finish();
} else if (item.getItemId() == R.id.action_bookmark) {
FragmentAdapter adapter = (FragmentAdapter) mViewPager.getAdapter();
PageFragment fragment = (PageFragment)adapter.instantiateItem(mViewPager,mViewPager.getCurrentItem());
fragment.getContent();
Toast.makeText(this, "Bookmark Added", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
Is there any way to check which icon set to options menu item also change it with another when clicked on it?
here is xml for options menu:
<item
android:id="#+id/action_bookmark"
android:title="Bookmark"
app:showAsAction="always|collapseActionView"
android:icon="#drawable/ic_bookmark_empty" />
onclicking i want to check which icon bookmark has and change it.
if you want to check which drawable is currently set you can use this code
item.getIcon().getConstantState().equals
(getResources().getDrawable(R.drawable.ic_bookmark_empty).getConstantState())
and for setting new drawable you can use this code
item.setIcon(R.drawble.ic_bookmark_empty)
You need to check the following condition in onOptionsItemSelected :
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
saveState();
finish();
} else if (item.getItemId() == R.id.action_bookmark) {
if(item.getIcon() ==R.drawable.ic_bookmark_empty)
{
// call bookmark code
item.setIcon(R.drawable.ic_bookmark_filled); // set your desired bookmark icon
} else {
// call remove bookmark code
item.setIcon(R.drawable.ic_bookmark_empty);
}
FragmentAdapter adapter = (FragmentAdapter) mViewPager.getAdapter();
PageFragment fragment = (PageFragment)adapter.instantiateItem(mViewPager,mViewPager.getCurrentItem());
fragment.getContent();
Toast.makeText(this, "Bookmark Added", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
You can use this code menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.ic_bookmark_empty));

Android: I can't make collapseActionView

I want to make something like that:
I try to make the popup menu whit the collapseview, y the action bar. but i try all the thing that i found on internet and no solution found. i didnt need suppoart android api less than 15.
this the main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="#string/action_settings"/>
<item android:id="#+id/action_search"
android:icon="#android:drawable/ic_dialog_email"
android:title="#string/hello_world"
android:showAsAction="always|collapseActionView"
/>
<item android:id="#+id/action_compose"
android:icon="#android:drawable/btn_star"
android:title="#string/hello_world"
android:showAsAction="never"
/>
<item android:id="#+id/action_compose2"
android:icon="#android:drawable/btn_star"
android:title="#string/hello_world"
android:showAsAction="never"
/>
</menu>
This my activity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar a = getActionBar();
a.setTitle("Mariano");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
MenuItem menuItem = menu.findItem(R.id.action_search);
MenuItemCompat.setOnActionExpandListener(menuItem, new OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem arg0) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem arg0) {
// TODO Auto-generated method stub
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return false;
}
}
If I understood correctly you want to open an Android Popup Menu by click on a Button. Then all you have to do is to add this to your MainActivity:
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(MainActivity.this, button1);
//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
int i = item.getItemId();
if (i == R.id.id1) {
//do something
return true;
}
else if (i == R.id.id2){
//do something
}
else if (i == R.id.id3) {
//do something
return true;
}
else if (i == R.id.id4) {
//do something
return true;
}else {
return onMenuItemClick(item);
}
});
popup.show();//showing popup menu
}
});//closing the setOnClickListener method
}

registerForContextMenu for menuItems

Ok I'm sure this is a dumb question but I couldn't find the answer online. I want to register one of the menu Items for a context Menu, but I don't know how to can't figure out how to access the MenuItem as a view. So when I click one of the buttons on the ActionBar of my application, I want a context menu to pop up. I'm guessing this has to be done in OnCreateOptionsMenu?
Edit: Update... Adding this code works partially but overrides my Drawable.
XML
<item android:id="#+id/Favorites"
android:title="favorite_label"
android:icon="#android:drawable/ic_menu_myplaces"
android:actionViewClass="android.widget.ImageButton"
android:showAsAction="always"
/>
Main Activity
FavoriteButton = (ImageButton) menu.findItem(R.id.Favorites).getActionView();
FavoriteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
registerForContextMenu(v);
}
});
Hi follow below link exmple link
ListView list = (ListView)findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.listitem, Countries);
list.setAdapter(adapter);
registerForContextMenu(list);
change registerForContextMenu(list); to registerForContextMenu(buttonname);
i hope it useful to you.
In the resource/menu/main.xml add the below code:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<menu>
<item
android:id="#+id/gray"
android:title="#string/gray" />
<item
android:id="#+id/green"
android:title="#string/green" />
<item
android:id="#+id/red"
android:title="#string/red" />
<item
android:id="#+id/orange"
android:title="#string/orange" />
<item
android:id="#+id/purple"
android:title="#string/dark_blue" />
</menu>
</item>
</menu>
and in the main activity you can access this by overridding the belo method:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.gray:
color = Color.parseColor("#FF666666");
return true;
case R.id.green:
color = Color.parseColor("#FF96AA39");
return true;
case R.id.orange:
color = Color.parseColor("#FFF4842D");
return true;
case R.id.purple:
color = Color.parseColor("#FF5161BC");
return true;
}
return super.onOptionsItemSelected(item);
}
Here is what I have made:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// "menu_main" is the menubar of my actionbar menu
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// "item" is the menu button I have pressed
int id = item.getItemId();
// "Settings" button
if (id == R.id.action_settings) {
return true;
}
// Difficulty button to change the difficulty of my game
else if (id == R.id.action_difficulty) {
View view = findViewById(R.id.action_difficulty);
registerForContextMenu(view);
openContextMenu(view);
}
return super.onOptionsItemSelected(item);
}
This works fine for me!
BUT! If your menubar button is behind the "three dots" button, the line
registerForContextMenu(view);
will crash your application. I'm figuring out why..

Handling a Menu Item Click Event - Android

I want to create an intent that starts a new activity once a Menu Item is clicked, but I'm not sure how to do this. I've been reading through the android documentation, but my implementation isn't correct..and some guidance in the right direction would help. I've listed my code below and commented out my problem areas, I think I'm invoking the wrong method.
package com.jbsoft.SimpleFlashlight;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.*;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.Button;
import android.widget.Toast;
public class SimpleFlashLightActivity extends Activity {
Button GreenButton; // Declare instances of buttons to use later
Button BlueButton;
private static final int OK_MENU_ITEM = Menu.FIRST;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BlueButton = (Button) findViewById(R.id.bluebutton);
BlueButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Display msg when user clicks Blue Button
showColorChangeMsg();
// Switch Activities on click
Intent blueintent = new Intent(SimpleFlashLightActivity.this,
BlueFlashLightActivity.class);
startActivity(blueintent);
}
});
//Install listener for second button
GreenButton = (Button) findViewById(R.id.greenbutton);
GreenButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Display msg when user clicks Green Button
showColorChangeMsg();
Intent greenintent = new Intent(SimpleFlashLightActivity.this,
GreenFlashLightActivty.class);
startActivity(greenintent);
}
});
;
/**************************************************************************************/
// Method Declarations // THIS IS WHERE I'M HAVING A PROBLEM
MenuItem AddColorButton = (MenuItem)findViewById(R.id.menu_insert);
boolean onOptionsItemSelected(AddColorButton) {
Intent intent = new Intent(SimpleFlashLightActivity.this,
BlueFlashLightActivity.class);
startActivity(intent);
return true;
;
};
/****************************************************************************************/
}
private void showColorChangeMsg()
{
Toast msgtoast = Toast.makeText(this.getBaseContext(), "SWITCH COLOR!",
Toast.LENGTH_LONG);
msgtoast.show();
}
private void showMsg(String msg) {
Toast toast = Toast.makeText(this, msg, Toast.LENGTH_LONG);
toast.show();
}
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.list_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case OK_MENU_ITEM:
showMsg("OK");
break;
}
return super.onOptionsItemSelected(item);
}
}
Add Following Code
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.new_item:
Intent i = new Intent(this,SecondActivity.class);
this.startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Menu items file looks like
res/menu/menu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<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"/>
</menu>
Java code looks like
src/MainActivity.java
#Override
public boolean onCreateOptionsMenu(Menu menu) {
present.
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);
}
And add following code to your AndroidManifest.xml file
<activity
android:name=".MyActivity"
android:label="#string/app_name" >
</activity>
I hope it will help you.
in addition to the options shown in your question, there is the possibility of implementing the action directly in your xml file from the menu, for example:
<item
android:id="#+id/OK_MENU_ITEM"
android:onClick="showMsgDirectMenuXml" />
And for your Java (Activity) file, you need to implement a public method with a single parameter of type MenuItem, for example:
private void showMsgDirectMenuXml(MenuItem item) {
Toast toast = Toast.makeText(this, "OK", Toast.LENGTH_LONG);
toast.show();
}
NOTE: This method will have behavior similar to the onOptionsItemSelected (MenuItem item)
This code is work for me
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
// add your action here that you want
return true;
}
else if (id==R.id.login)
{
// add your action here that you want
}
return super.onOptionsItemSelected(item);
}
This is how it looks like in Kotlin
main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never" />
<item
android:id="#+id/action_logout"
android:orderInCategory="101"
android:title="#string/sign_out"
app:showAsAction="never" />
Then in MainActivity
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
return true
}
This is onOptionsItemSelected function
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when(item.itemId){
R.id.action_settings -> {
true
}
R.id.action_logout -> {
signOut()
true
}
else -> return super.onOptionsItemSelected(item)
}
}
For starting new activity
private fun signOut(){
MySharedPreferences.clearToken()
startSplashScreenActivity()
}
private fun startSplashScreenActivity(){
val intent = Intent(GrepToDo.applicationContext(), SplashScreenActivity::class.java)
startActivity(intent)
finish()
}
Replace Your onOptionsItemSelected as:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case OK_MENU_ITEM:
startActivity(new Intent(DashboardActivity.this, SettingActivity.class));
break;
// You can handle other cases Here.
default:
super.onOptionsItemSelected(item);
}
}
Here, I want to navigate from DashboardActivity to SettingActivity.

Android, How to create option Menu

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

Categories

Resources