I've been trying to add a functionality to my android application such that when I click a button, menu listing should be visible:
Here is my code:
menu.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="com.example.MainActivity" >
<item android:id="#+id/action_onthego_sentence"
android:title="settings"
android:orderInCategory="100"
app:showAsAction="never" />
</menu>
From the main activity, upon clicking a button, I do:
button.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick( View view )
{
runOnUiThread( new Runnable()
{
#Override
public void run()
{
openOptionsMenu();
}
} );
}
} );
What I need is:
As shown in the image, I'd like to see the menu is opened. Any suggestions please?
If you are using customized toolbar in your app, then the following way will be useful,
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
toolbar.showOverflowMenu();
}
}, 500);
Use:
MainActivity.this.openOptionsMenu();
Then, check your toolbar if is this okay.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.acercade_activity);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// MenuInflater inflater = getMenuInflater();
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
//case R.id.action_settings:
// return true;
case R.id.perfil:
drawerLayout.openDrawer(Gravity.LEFT);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Use this in your menu layout:
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="Setting"
app:showAsAction="ifRoom" />
Hello Dear if you are using toolbar following code
toolbar.showOverflowMenu();
And other wise you can directly call
MainActivity.this.openOptionsMenu();
Try the below solution It will be display click on the button menu listing should be visible:
res/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:id="#+id/action_changeLang"
android:orderInCategory="100"
android:title="Change Lang" />
<item
android:id="#+id/action_color"
android:orderInCategory="100"
android:title="Select color" />
<item
android:id="#+id/action_applist"
android:orderInCategory="100"
android:title="App List" />
</menu>
MainActivity.java
#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 boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_changeLang:
// Add your code
break;
case R.id.action_color:
// Add your code
break;
case R.id.action_applist:
// Add your code
break;
}
return super.onOptionsItemSelected(item);
}
Try to use above solution. It will work for me
Use Activity.openOptionsMenu() to open menu programmatically, but you may need to post delay to call it. like below
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
openOptionsMenu();
}
}, 1000);
If you need to open sub menu automatically. you can call menu.performIdentifierAction after openOptionsMenu, like below
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
openOptionsMenu();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mainMenu.performIdentifierAction(R.id.submenu, 0);
}
}, 500);
}
}, 1000);
Android Dev efficiency tools: https://play.google.com/store/apps/details?id=cn.trinea.android.developertools
Android Open Source Projects: https://p.codekk.com/
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 switch in my app toolbar to provide an option to the user to change the language.
When I am using the switch, the onCheckedChanged method is not working.
Further, it looks to me that onOptionsItemSelected is also not being hit as I don't see any log message on the screen.
Please note that the app is not crashing when I use the switch.
The clicks on options present inside the overflow menu are working properly. I am getting the log in those cases.
Switch aSwitch;
RelativeLayout langSwitch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
context = this;
// Removed non relevant code here.
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
Log.d("tag_id",String.valueOf(id));
langSwitch = findViewById(R.id.app_bar_switch);
aSwitch = langSwitch.findViewById(R.id.langSwitch);
aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (!b){
//Language1 code
Toast.makeText(context,"Language1 Selected",Toast.LENGTH_SHORT).show();
}else{
//Language2 code
Toast.makeText(context,"Language2 Selected",Toast.LENGTH_SHORT).show();
}
}
});
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.savedPost){
Intent intent = new Intent(this,SavedPost.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
Below is my 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="com.app_name.android.app_name.MainActivity">
<item
android:id="#+id/app_bar_switch"
android:orderInCategory="2"
android:title=""
app:actionLayout="#layout/switch_item"
app:showAsAction="always" />
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never" />
<item
android:id="#+id/savedPost"
android:checkable="false"
android:orderInCategory="4"
android:title="#string/saved_post" />
</menu>
This is my layout file for switch item.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Switch
android:id="#+id/langSwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textOff="#string/switch_text_off"
android:textOn="#string/switch_text_on"
android:focusable="true"
android:clickable="true"/>
</RelativeLayout>
Additional information.
If I create another menu item (code below) with showAsAction 'always' and click on this once, now when I use the switch the Toast message comes. I am clueless here as to why is it not happening for the first time. Also, how do I make it work without this menu item.
<item
android:id="#+id/english"
android:orderInCategory="3"
android:title="#string/switch_text_on"
app:showAsAction="always" />
To inflate an external layout over ActionBar that seems to first creating a view that holds your ChildView for your layout
like Example
RelativeLayout item = (RelativeLayout)findViewById(R.id.item);
View child = getLayoutInflater().inflate(R.layout.child, null);
item.addView(child);
Try this in your code
Switch aSwitch;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
View sw = menu.findItem(R.id.app_bar_switch).getActionView();
aSwitch = (Switch) sw.findViewById(R.id.langSwitch);
aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (!b){
//Language1 code
Toast.makeText(context,"Language1 Selected",Toast.LENGTH_SHORT).show();
}else{
//Language2 code
Toast.makeText(context,"Language2 Selected",Toast.LENGTH_SHORT).show();
}
}
});
return true;
}
Try
(compoundButton.isChecked())
In boolean
Or
just try another version of setonCheckedChangedListner
Example:
aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){#Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if (!compoundButton.isSelected()) { Log.i("Yeah" , "Is Not Selected"); invertLock(-1); } else { if (Utilities.isLockEnabled(context)) { Log.i("Yeah" , "Is Locked"); Utilities.showLockEnabled(context); } else { Log.i("Yeah" , "Is Not Locked"); invertLock(1); } } }
I'm a new one in Android. I have some problems with showing menu. I don't see three dots in right corner in my screen. Please, help me to understand my mistake. THANK YOU A LOT!
Activity:
public class MainActivity extends AppCompatActivity {
private EditText numb1;
private EditText numb2;
private Button btn_sum;
private Button btn_extr;
private Button btn_mult;
private Button btn_div;
private TextView result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*some code*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.reset:
numb1.setText("");
numb2.setText("");
break;
case R.id.exit:
fileList();
break;
}
return super.onOptionsItemSelected(item);
}
}
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:id="#+id/reset"
android:title="#string/reset"
app:showAsAction="never"/>
<item android:id="#+id/exit"
android:title="#string/exit"
app:showAsAction="never"/>
</menu>
Menu Items are not showing on Action Bar
Check this answer
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:showAsAction="ifRoom|withText"
android:title="#string/action_option1"/>
<item
android:id="#+id/action_settings34"
android:orderInCategory="100"
android:showAsAction="ifRoom|withText"
android:title="#string/action_option2"/>
<item
android:id="#+id/action_settings3"
android:orderInCategory="100"
android:showAsAction="ifRoom|withText"
android:title="#string/action_option3"/>
</menu>
Use this code in your activity, but you should have action bar in it.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.your_menu, menu);
return true;
}
if you run your application on oldest version of samsung or other the three DOTS is not appear on ActionBar
so try to click on Option Key on mobile
The solution to appear Three DOTS
call this method in your application class' onCreate method
private void makeActionOverflowMenuShown() {
//devices with hardware menu button (e.g. Samsung Note) don't show action overflow menu
try {
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if (menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
}
i am also new to android i guess u wrote onCreateOptionsMenu(Menu menu) inside on create
try this
public class MainActivity extends AppCompatActivity {
private EditText numb1;
private EditText numb2;
private Button btn_sum;
private Button btn_extr;
private Button btn_mult;
private Button btn_div;
private TextView result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*some code*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.reset:
numb1.setText("");
numb2.setText("");
break;
case R.id.exit:
fileList();
break;
}
return super.onOptionsItemSelected(item);
}
}
You have done the minor mistake while creating the option menu .you should call the onCreateOptionsMenu() and onOptionsItemSelected() method outside the onCreate(Bundle savedInstanceState) method. you may check the following example :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.reset:
break;
case R.id.exit:
fileList();
break;
}
return super.onOptionsItemSelected(item);
} }
Help me to understand my mistake - Sure
The Main culprit is in your menu XML file app:showAsAction="never" this line replace this line with app:showAsAction="ifRoom"
here showAsAction is set to never means you tell that don't show my menu in action bar if you replace with "ifRoom" means you said show my all menu in action bar and if there is space for all my menus
I am newbie to Android Development, I am looking to get an one more menu on ActionMode, that is along with cut,copy,selectAll. I want to add "mark" to this menu.
So I added an item in main.xml below is the following code of it.
<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="com.example.fn.MainActivity" >
<item
android:id="#+id/action_settings1"
android:orderInCategory="100"
android:onClick="onContextualMenuItemClicked"
android:title="Mark"
app:showAsAction="ifRoom"/>
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never"/>
</menu>
This was tested and works fine in most of the phones, but in few phones it long pressing on texts, it shows the message
unfortunately, app has stopped
there is no other process and my app was closed suddenly.
I am not sure why? can someone assist me here?
If I remove this following line from that item, it will works.
android:onClick="onContextualMenuItemClicked"
but I am triggering that onclick in Activity,
public void onContextualMenuItemClicked(MenuItem item) {
/*switch (item.getItemId()) {
case R.id.mark:
webView.loadUrl("javascript:doMouseUp();");
break;
default:
System.out.println("default");
break;
}
if (mActionMode != null) {
mActionMode.finish();
}*/
}
Update
#Override
public void onActionModeStarted(ActionMode mode) {
if (mActionMode == null) {
mActionMode = mode;
Menu menu = mode.getMenu();
menu.clear();
mode.getMenuInflater().inflate(R.menu.main, menu);
}
super.onActionModeStarted(mode);
}
It looks like you are extending the MainActivity with ActionBarActivity. This is supports only after the Android KitKat. In version 5 and later it doesn't make problem.
You need to extend the MainActivity with Activity, then it will works for you.
public class MainActivity extends Activity {
Then, You need to have separate xml file (myMenu.xml) under /res/menu in your project structure.
myMenu.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="com.example.fn.MainActivity" >
<item
android:id="#+id/mark"
android:showAsAction="always"
android:onClick="onContextualMenuItemClicked"
android:title="Mark">
</item>
</menu>
Copy this method and change as per your need and replace in Activity.
#Override
public void onActionModeStarted(ActionMode mode) {
if (mActionMode == null) {
mActionMode = mode;
Menu menu = mode.getMenu();
menu.clear();
mode.getMenuInflater().inflate(myMenu, menu);
}
super.onActionModeStarted(mode);
}
That's all, hope now it works for you.
You can try something dynamic!!
Override this method
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
CreateMenu(menu);
return true;
}
Make this Method
private void CreateMenu(Menu menu) {
MenuItem mnu1 = menu.add(0, 0, 0, "Delete");
{
//mnu1.setIcon(R..ic_menu_delete);
//R.drawable.ic_menu_delete
mnu1.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
MenuItem mnu2 = menu.add(0, 1, 1, "Edit");
{
//mnu2.setIcon();
mnu2.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
}
}
And for onClick override this
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return MenuChoice(item);
}
and create this method
private boolean MenuChoice(MenuItem item) {
switch (item.getItemId()) {
case 0:
//your method here
return true;
case 1:
//your method here
return true;
}
return false;
}
My code creates 2 options
I have an item on ActionBar.
When the user click on it, dialog should pop up.
So I'm trying to select this parts by this code
mItem1 = (Item) findViewById(R.id.about)
However, I get this error so that I cannot define.
Cannot cast from View to ClipData.Item
Why is that? How can I fix?
res/menu/main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/about"
android:orderInCategory="100"
android:showAsAction="never"
android:title="About this App"/>
</menu>
After the comment
I have no idea what ClipData is about. All I want to do is selecting About this App on ActionBar as a trigger to show dialog. Then I'm facing this problem. Could you use my code and show me?
I try to answer the question as following:
Create a menu-layout-file main.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/about"
android:orderInCategory="100"
android:showAsAction="never"
android:title="#string/about"/>
</menu>
Create the activity MainActivty:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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.about:
new AlertDialog.Builder(this).setTitle("About").setMessage("Text about about").setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
}).show();
break;
}
return true;
}
}
ClipData.Item is not derived from the View class. findViewById has to return a View or a subclass of a View. Hence, the cannot cast error.