Remove Toolbar items on runtime - android

I have a Toolbar within my app which I would like to modify it contents dynamically, during the app execution (in other words, on run-time).
For example, the app is capable of taking and previewing photos; once that photos are previewed, the user is able to select some photos and perform a sending action to a server. I want also to make the user able to delete photos once that some of them are selected and for doing that I would like that the "delete" item on the action bar (identifiable via the trash icon) will be visible only when one or more photos are selected.
Is this possible to do?
If yes, how?
In other words and, more generically, I want to control items (visibility) in the toolbar, setting the code as they will be "visible" only when some conditions are "true" (in the example above, when photos are selected or, in a different example, when user is logged) and invisible when they are "false" (when user isn't logged).
For now I just need to "remove" (or make invisible) items in the Toolbar, but it will be useful also to know if is possible to add items in the toolbar on run-time.
I'm adding some code which can help to understand the problem.
app_bar.xml file in "/res/layout", which graphically defines the Toolbar
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:elevation="4dp"
android:theme="#style/ToolbarTheme" />
menu_resources.xml file, which defines the Toolbar items
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- "User favourite function", should appear as action button if possible -->
<item
android:id="#+id/action_app_icon"
android:icon="#mipmap/ic_launcher"
android:title="#string/action_bar_app_icon"
app:showAsAction="always" />
<!-- Settings, should always be in the overflow -->
<item
android:id="#+id/action_delete"
android:icon="#drawable/trash"
android:title="#string/action_bar_delete"
app:showAsAction="always"/>
<!-- Settings, should always be in the overflow -->
<item
android:id="#+id/action_settings"
android:icon="#drawable/settings"
android:title="#string/action_bar_settings"
app:showAsAction="never"/>
<!-- About, should always be in the overflow -->
<item
android:id="#+id/about"
android:icon="#android:drawable/ic_dialog_info"
app:showAsAction="never"
android:title="#string/action_bar_about"/>
Part of the activity in which the toolbar is
public class myClass extends AppCompatActivity implements View.OnClickListener {
// Instantiating a toolbar
private Toolbar toolbar;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_class);
// Adding toolbar to the activity
toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
// Get a support ActionBar corresponding to this toolbar
ActionBar ab = getSupportActionBar();
// Enable the Up button
ab.setDisplayHomeAsUpEnabled(true);
}
// The method that creates an options menu
#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_resource, menu);
// This make the delete item invisible
menu.findItem(R.id.action_delete).setVisible(false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
// Perform the settings action
return true;
case R.id.about:
// Perform the about
return true;
case R.id.action_delete:
deletePhotos();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public static void manageSelection(Boolean state, int position){
if (photoArray.getNumberSelected() == 0) {
// disable the trash icon and its functionality;
} else {
// enable the trash icon with its functionality;
}
}
// This method allows to deleteItems images to the array
public void deletePhotos() {
//code for deleting photos
}
}
Thanks for your time.

Try this code in your activity please:
public class ActivityClass extends AppCompatActivity {
MenuItem menuItem; // Make global toolbar's menuItem
.
.
.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_layout, menu);
menuItem = menu.findItem(R.id.toolbar_action_button) // Your toolbar´s button ID and save it in your global menuItem
return super.onCreateOptionsMenu(menu);
}
public void showMenuItem(){
menuItem.setVisible(true); // Call this method in runtime when you need show it
}
public void hideMenuItem(){
menuItem.setVisible(false); // Call this method in runtime when you need hide it
}
[EDIT]
Thanks to Alessandro Iudicone´s comment we have an alternative way to get the toolbar´s menu too without the global MenuItem but only global Toolbar instance:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_layout, menu);
return super.onCreateOptionsMenu(menu);
}
public void showMenuItem(){
toolbar.getMenu().findItem(R.id.toolbar_actio‌​n_button).setVisible‌​(true);
}
public void hideMenuItem(){
toolbar.getMenu().findItem(R.id.toolbar_actio‌​n_button).setVisible‌​(false);
}
Hope it helps :)

For hiding the icon:
toolbar.findViewById(R.id.menu_item_id).setVisibility(View.INVISIBLE);
For adding a view to the toolbar:
TextView textView = new TextView(MainActivity.this);
textView.setText("Hello World");
toolbar.addView(textView);
This only works for views on the toolbar itself, not for the overflow menu. You'll probably have to use code found in this stack overflow answer if you want to mess with the overflow menu: Android Toolbar overflow menu view id

Related

Get the ID of a MenuItem in a toolbar

I have a "menu" resource "menu_test" with the following 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"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".TestActivity" >
<item android:id="#+id/hideshow"
android:title="Body visbility"
android:orderInCategory="100"
android:icon="#drawable/showicon"
app:showAsAction="always" />
</menu>
In my activity.java I inflate the toolbar in the "onCreate" function and add a click listener:
private Toolbar toolbar;
...
toolbar = (Toolbar)findViewById(R.id.toolbarId);
toolbar.inflateMenu(R.menu.menu_test);
toolbar.setOnMenuItemClickListener(this);
I would like to get the ID of "hideshow" and change the icon:
testItem = (MenuItem) toolbar.findViewById(R.id.hideshow);
testItem.setIcon(R.drawable.hideicon);
However to app crashes when getting the ID in the first line. In the click listener function it works fine, since the ID is provided internally with the click:
public boolean onMenuItemClick(MenuItem item)
item.setIcon(R.drawable.hideicon);
So how can I change the icon within the onCreate function? ("findItem" does not work, since toolbar is not a menu)
I may be easier to add the menu items programmatically so you can maintain a reference to them:
public class MainActivity extends AppCompatActivity {
private static final int MENU_SETTINGS = Menu.FIRST;
MenuItem menuItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menuItem = menu.add(0, MENU_SETTINGS, 0, R.string.action_settings).setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_SETTINGS:
// DO SOMETHING
break;
}
return super.onOptionsItemSelected(item);
}
}
As the other answers and comments indicate, one needs a reference from onCreateOptionsMenu or onPrepareOptionsMenu.
In my case, this would require a lot of code rewrite, as this is an old project, where everything is based on using toolbars instead of menus.
However, I found an easy solution:
Instead of finding the ID and changing the icon, I created several instances of menu_test[1 .. n].xml with different icons and simply use inflateMenu(R.menu.menu_test[1 .. n]) depending on the icon I need.
If you write new code, use the solution from Abtin Gramian, so I mark that as the proper answer.

How to create optionmenu for android 3.0 and higher version and option menu icon not showing in higher version mobiles

How to create optionmenu for Android 3.0 and higher version mobiles?
I am trying to create options menu in my Android program. I am using the following code to inflate options menu. option menu icon not showing in higher version mobiles..
public class MainScreenTab extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "Merchants", "Personal Payee" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_screen_tab_layout);
//Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu); //inflate our menu
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
// switch(item.getItemId()) {
int id = item.getItemId();
if (id == R.id.item_refresh) {
Intent i = new Intent(MainScreenTab.this,ListMerchantType.class);
startActivity(i);
return true;
}
else if (id == R.id.item_save) {
Intent i = new Intent(MainScreenTab.this,ListPayee.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
}
You just need to use this Reflection method to force your icon in the ActionBar
public static void forceOverFlowIconInActionBar(Activity mActivity)
{
try
{
ViewConfiguration config = ViewConfiguration.get(mActivity);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if(menuKeyField != null)
{
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
Try this one. import java.lang.reflect.Field; And on your onCreateOptionsMenu() method just simply add:
if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
try {
Field field = menu.getClass().getDeclaredField("mOptionalIconsVisible");
field.setAccessible(true);
field.setBoolean(menu, true);
} catch (Exception ignored) {
ignored.printStackTrace();
}
}
and don't forget to add this to your xml menu android:icon="#drawable/blah_blah" . Hope it helps. And don't forget to up-vote if it is helpful.
Menus: Generally a list of commands or facilities displayed on screen. It is a common user interface for the user. If you want to provide a familiar and consistent user experience you should use Menus in your activity. It is beginning with android 3.0(Api level 11). So design and user experience my change for device to device that is depends on the Menu apis.
There mainly there menus in the android. Those are Options menu, Context menu, Popup Menu.
Options menu:
Options menu is a collection of menu items for an activity. The place where you locate icons that is very impact to the app. Such menu items are search, settings, compose email.
If you are developing the options menu for Android 2.3 and lower user can reveal the options menu by pressing menu button. On the 3.0 and higher the options menu items as a combination of action bar items. Beginning with Android 3.0, the Menu button is deprecated (some devices don't have one), so you should migrate toward using the action bar to provide access to actions and other options.
Creating Options Menu in android
Simply options menu is where you should you include options and other actions what are relevant to activity. The item in the options menu is depends on the version you are using.
If it is below 3.0 that comes when you press the menu buttons. If it is higher that will comes to the top of the screen. Means that will include with the action bar screen.
You can declare items for the options menu from either your Activity subclass or a Fragment subclass. At one time if you declare both the items in the activity then that will appear one followed another. You can also reorder the menu items in the android:orderInCategory attribute in each you need to move.
To specify a menu item in the activity first you need to override one method. That method is onCreateOptionsMenu() . This mehtod fragments provide their own onCreateOptionsMenu() callback.
Example:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.game_menu, menu);
return true;
}
We can perform add and retrieve options in the menu item api by using add() and findItem().
Handling click events in onCreateOptionsMenu():
If you want to provide a click event on the menu items the system calls onOptionsItemSelected. In that method you can identify which item you are selected by using item.getItemId(). which returns the unique ID for the menu item (defined by the android:id attribute in the menu resource or with an integer given to the add() method). You it is matched you can perform your action whatever you want.
Example:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.new_game:
newGame();
return true;
case R.id.help:
showHelp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
When you successfully handle the menu item that will returns true. If not handle that item that will you should call the superclass implementation of onOptionsItemSelected().
Changing menu items at runtime:
When you call onCreateOptionsMenu() that is displaying simple onCreateOptionsMenu(). you can not change the items in the run time. If you want to change the items in the run time you need to call onPrepareOptionsMenu() method. This method passes you the Menu object as it currently exists so you can modify it, such as add, remove, or disable items.
Example Project:
Open your eclipse and create one project name called OptionsMenu.
In that open you menu folder in the resource folder. In the main.xml file add how many items you want. You can get main.xml file below.
Main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="#+id/menu_settings" android:orderInCategory="100"
android:showAsAction="never" android:title="#string/menu_settings"/>
<item android:id="#+id/item1" android:title="Tutorial 1"></item>
<item android:id="#+id/item2" android:title="Tutorial 2"></item>
<item android:id="#+id/item3" android:title="Tutorial 3"></item>
<item android:id="#+id/item4" android:title="Tutorial 4"></item>
<item android:id="#+id/item5" android:title="Tutorial 5"></item>
</menu>
Here i used #string/menu_settings so you can add that item in the strings.xml file.
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">OptionsMenu</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
</resources>
Once that is done open your main activity. In that write the onCreateOptionsMenu method for adding the menu item to the activity. Once that is done if you want to give click events you write onOptionsItemSelected. You can get the complete code below.
MainActivity
package com.tutorialindustry.optionsmenu;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
public 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;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item1:
Toast.makeText(this, "Tutorial 1 Selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.item2:
Toast.makeText(this, "Tutorial 2 Selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.item3:
Toast.makeText(this, "Tutorial 3 Selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.item4:
Toast.makeText(this, "Tutorial 4 Selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.item5:
Toast.makeText(this, "Tutorial 5 Selected", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Once that is done run you project that you can get the below output. In this way we can perform options menu in the android.

Options Menu not displaying on ActionBar

I wanted to display Menu in ActionBar using ActionBarActivity.
I am getting options menu while clicking options button instead of displaying in the top of action bar.
I need the options menu at top instead of clicking the options menu from 2.3 onwards
My Code :
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setSubtitle("mytest");
actionBar.setTitle("Testing");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_action, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_one:
Toast.makeText(this, "clicked search", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
My XML file :
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/menu_item_one"
android:icon="#drawable/ic_launcher"
android:showAsAction="always"
android:title="#string/action_settings"/>
<item
android:id="#+id/menu_item_two"
android:icon="#drawable/ic_launcher"
android:showAsAction="always"
android:title="#string/action_settings"/>
</menu>
Try it:
Create XML file on "../res/menu/menu_main.xml"
manu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/menu_settings"
android:showAsAction="never"
android:icon="#android:drawable/ic_menu_settings"
android:title="#string/menu_settings"/>
</menu>
The option "never" on "showAsAction", important, if you put that the option always show on ActionBar.
Then now we must asociate this option on the MainActivity.java (class whatever you want).
MainActivity.java
public class MainActivity extends Activity {
...
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Now that we define the elements of our action bar is knowing how to respond to keystrokes made ​​by the user about them.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
Log.i("ActionBar", "Settings!");;
//open Activity,Fragments or other action
return true;
default:
return super.onOptionsItemSelected(item);
}
}
If you have morer options on your menu only add item on XML menu_main.xml and on the principal class add other "case".
For Example:
MainActivity.java
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_save:
Log.i("ActionBar", "Save!");;
//open Activity,Fragments or other action
return true;
case R.id.menu_settings:
Log.i("ActionBar", "Settings!");;
//open Activity,Fragments or other action
return true;
default:
return super.onOptionsItemSelected(item);
}
}
menu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/menu_settings"
android:showAsAction="never"
android:icon="#android:drawable/ic_menu_settings"
android:title="#string/menu_settings"/>
<item
android:id="#+id/menu_save"
android:showAsAction="never"
android:icon="#android:drawable/ic_menu_save"
android:title="#string/menu_save"/>
</menu>
It is possible that this is because your device has an options button that would open the menu, so Android don't draw the launcher icon.
http://blog.vogella.com/2013/08/06/android-always-show-the-overflow-menu-even-if-the-phone-as-a-menu/
Try with return super.onCreateOptionsMenu(menu); instead of return true in your onCreateOptionsMenu method according to below android document...
http://developer.android.com/guide/topics/ui/actionbar.html#ActionItems
As per above android document...
The ActionBar APIs were first added in Android 3.0 (API level 11) but they are also available in the Support Library for compatibility with Android 2.1 (API level 7) and above.
So, If you want ActionBar in android 2.3 then you have to use Android Support Library.
Edit:
Your menu XML would need to look like this:
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto"
>
<item android:id="#+id/item_menu_ok"
android:icon="#drawable/ic_action_ok"
android:title="#string/ok"
yourapp:showAsAction="always"/>
<item android:id="#+id/item_menu_cancel"
android:icon="#drawable/ic_action_cancel"
android:title="#string/cancel"
yourapp:showAsAction="always"/>
</menu>
Replace yourapp with your app name or any namespace.
I'm not 100% sure, but it looks like your menu XML file should have a menu in it. In the menu, add the items. Like this:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_menu" >
<item...
<item...
</menu>
Perhaps this works.
There are also a few other things to remember in general. Android decides by itself what to show in the ActionBar (depending on what fits there and other parameters). What does not fit in the ActionBar goes into the overflow.
Do this in your oncreate()
ActionBar actionBar = getActionBar();
actionBar.show();
This should do what you want.
Action Bar
Ok, let's try another answer. If, for whatever reason, Android decides not to show the items in the action bar, then what your are seeing is indeed the correct behaviour. Items not in the action bar are shown in overflow.
One reason items don't show in the action bar is because they don't have a icon defined.
You do define an icon, as this,
android:icon="#drawable/ic_launcher"
and I suspect this is the problem. The launcher icon is of different size (larger) than the action bar items (smaller). Try defining the icon in correct size and see if it is displayed.
http://developer.android.com/design/style/iconography.html
Edit: There is an action bar icon pack to get you started so you can test to see if it works. Download it and use eclipse to import some icon..

Create custom menu on webview

How to create custom menu for webview when longpress event occur as shown in image at the top?
public class MainActivity extends Activity {
private String data;
private WebView webview;
private String clipdata = "";
private boolean mark_text;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView) this.findViewById(R.id.webView1);
data = "The entire plan-to-produce process, including enterprise-level planning and scheduling, plant-level operations, manufacturing execution, batch manufacturing, and quality management. Capabilities for Big Data management and process integration support the use of real-time data from the shop floor to maintain batch traceability and genealogy. Embedded quality and compliance controls enable process manufacturers to manage exceptions and address nonconformance through corrective and preventive actions for batches. Leveraging mobile and cloud as well ![enter image description here][2]as on-premise technologies, this level of production control helps increase throughput, set predictable and shorter cycle times, improve asset utilization, and help ensure that inventory targets are met.</body></html>";
webview.loadDataWithBaseURL("", data, "text/html", "UTF-8", "");
}
#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);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
Toast.makeText(this, "action_search selected", Toast.LENGTH_SHORT)
.show();
return true;
case R.id.action_settings:
Toast.makeText(this, "action_settings selected", Toast.LENGTH_SHORT)
.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
I have update answer with my code. plz check it and say how how can I disable this default action bar and add my own action bar but at the same time text selection functionality should work.
This is called a Contextual Action Bar, it's an overlay on top of the default action bar.
There is a good tutorial here which describes how to work with it.
To get own action bar to work there while still keeping the selection functionality is going to be tricky to say the least I'm afraid...
To add actions to the action bar, create a new XML file in your project's res/menu/ directory.
main_activity_actions.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- Search, should appear as action button -->
<item android:id="#+id/action_search"
android:icon="#drawable/ic_action_search"
android:title="#string/action_search"
android:showAsAction="ifRoom" />
<!-- Settings, should always be in the overflow -->
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
android:showAsAction="never" />
</menu>
Add the Actions to the Action Bar
To place the menu items into the action bar, implement the onCreateOptionsMenu() callback method in your activity to inflate the menu resource into the given Menu object. For example:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
Respond to Action Buttons
When the user presses one of the action buttons or another item in the action overflow, the system calls your activity's onOptionsItemSelected() callback method. In your implementation of this method, call getItemId() on the given MenuItem to determine which item was pressed—the returned ID matches the value you declared in the corresponding element's android:id attribute.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
Toast.makeText(this,"action_search selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.action_settings:
Toast.makeText(this,"action_settings selected",Toast.LENGTH_SHORT).show();
return true;
default:
return super.on
OptionsItemSelected(item);
}
}
for further guidance refer the official doc
first create your own ActionModeCallBack then you need to create a class and extend WebView and overwrite this method:
public ActionMode startActionMode(ActionMode.Callback callback)
{
actionModeCallback = new CustomizedSelectActionModeCallback();
return super.startActionMode(actionModeCallback);
}
update: look at this
It's work for me...

How to disable/hide three-dot indicator(Option menu indicator) on ICS handsets

How to disable/hide three-dot indicator(Option menu indicator) on ICS handsets which does't have menu button. ?
I am running application as <uses-sdk android:minSdkVersion="5"/> in Manifest, code is compiled with 4.0. Three-dot indicator shows on every screen.
Example for preference activities i don't want show Three-dot indicator, since it does't have any menu options.
Adding android:targetSdkVersion="14" in manifest it works. However don't want hide/remove three dots button on all screens . Only in preference activities don't want to show this three dots button.
Override onPrepareOptionsMenu() in the fragment of the preference with this:
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item= menu.findItem(R.id.menu_settings);
item.setVisible(false);
super.onPrepareOptionsMenu(menu);
return true;
}
if you have more then one item set all the items visibility flag to false
and add the command setHasOptionsMenu(true);
to the onCreate command
after you will set all the visibility of the items to false the menu will disappear
on activity, the only difference is the onPrepareOptionsMenu is boolean and you don't need to add the setHasOptionsMenu(true); command on the creation
I just deleted the method :
#Override
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
then that three-dot-menu goes away (:
Hope it helps.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return false;
}
There is no way to show/hide "three-dot" menu indicator for a single activity. You can hide this menu indicator only for entire app by specifying android:targetSdkVersion="14" (or above) in your manifest file.
However, this menu indicator is not showing on preferences activity if it extends from native android.preference.PreferenceActivity class. I have this scenario implemented in a few of my apps, and it works perfectly.
I assume you are using some custom preferences implementations which does not extends from PreferenceActivity. Android Dev Team suggests to always use PreferenceActivity for any preferences in your applications.
Way too late to the party here, I was trying to remove all my menu items and the 3-dots(option menu indicator), I did differently than the solution given here I am surprised that nobody had told it. There is a visibility tag that can be set to false and no changing of code in activity is required visibility=false does the trick
in res / menu /..
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
visibility=false
android:title="#string/action_settings"/>
override method and return false remember of not call super
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return false;
}
Remove this item in res / menu / main.xml
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="#string/action_settings"/>
In addition: do not add an item that has showAsAction="never"- this will avoid the dots from showing. If you have more items than can not be shown at once the dots will be there again (and they are items that are flagged ifRoom).
Following code worked for my app. Tried on Samsung Galaxy S4 (Android 4.3) and Nexus 4 (Android 4.2):
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item= menu.findItem(R.id.action_settings);
item.setVisible(false);
return true;
}
for hiding 3 dots in actionbar/ toolbar
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_dash_board_drawer, menu);
return false; //for visible 3 dots change to true, hiding false
}
You can actually change the Android targetVersion thus forcing the 3-dot menu to either hide or show. You need to override onCreate of your Activity like this :
#Override
public void onCreate(Bundle savedInstanceState) {
getApplicationInfo().targetSdkVersion = 10; // To enable the 3-dot menu call this code before super.OnCreate
super.onCreate(savedInstanceState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
getApplicationInfo().targetSdkVersion = 14; // To disable the 3-dot menu call this code before super.OnCreate
super.onCreate(savedInstanceState);
}
Tested on Android 4.x.x and Android 3.0
I just excluded the "onCreateOptionsMenu"-method:
#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_planos, menu);
return true;
}
If you simply want to hide the button, this solution is a bit of a hack but works across all versions of Android (using AppCompat) and doesn't affect your other menu items:
styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light">
...
<item name="android:actionOverflowButtonStyle">#style/AppTheme.Overflow</item>
<!-- If you're using AppCompat, instead use -->
<item name="actionOverflowButtonStyle">#style/AppTheme.Overflow</item>
</style>
<style name="AppTheme" />
<style name="AppTheme.Overflow">
<item name="android:src">#null</item>
</style>
If you want the Overflow button hidden only on some screens, you could make this an alternate theme (change AppTheme above to AppTheme.NoOverflow) that only certain activities use :
AndroidManifest.xml
<activity android:name=".NoOverflowActivity"
android:theme="#style/AppTheme.NoOverflow" >
This effectively just makes the icon have no width and height. I rarely recommend opposing design guidelines but in my scenario we used dedicated hardware that did not properly report a menu button was present.
Just want to improve #war_hero answer.
If You wanna set the visibility on run time You can use oncreateoptions menu parameter like this
Menu overflow;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mymenu, menu);
this.overflow = menu;
return super.onCreateOptionsMenu(menu);
}
and then make a function to show or hide any menu item according to the index. for e.g.
public void hideorShowMenuItems(boolean bool){
overflow.getItem(1).setVisible(bool);
overflow.getItem(2).setVisible(bool);
overflow.getItem(3).setVisible(bool);
overflow.getItem(4).setVisible(bool);
overflow.getItem(5).setVisible(bool);
}
Copy paste this code in main.xml in menu folder
you just need to make the item android:visible="false"
<?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_settings"
android:orderInCategory="100"
android:visible="false"
android:title="#string/action_settings"
app:showAsAction="never" />
</menu>
Should be:
<item
android:id="#+id/linearlayout_splash"
android:orderInCategory="100"
android:showAsAction="never"
android:visible="false"
android:title="#string/action_settings"/>
If MainActivity is
public class MainActivity extends AppCompatActivity
In MainActivity Class, Remove the below code.
#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) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
Do it like this.
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(leftDrawer);
return (!drawerOpen);
}
I am checking if my navigation drawer is visible I will hide the menu and vice versa. You can use it according to you requirement. Hope this helps. Happy Coding. :)
This is how I find a solution of mine. It maybe helpful.
#Override
public boolean onKeyDown(int keycode, KeyEvent event ) {
//KEYCODE_MENU
if(keycode == KeyEvent.KEYCODE_MENU){
/* AlertDialog.Builder dialogBuilder
= new AlertDialog.Builder(this)
.setMessage("Test")
.setTitle("Menu dialog");
dialogBuilder.create().show();*/
return true;
// finish();
}
return super.onKeyDown(keycode,event);
}
I just used
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
Where R.menu.main is only an empty menu xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" ></menu>

Categories

Resources