I am using Java and Android Studio. I need to change an image on the actionbar. What I need to do is to change the image I am displaying on the actionbar based on a reading received from a remote sensor. Therefore, I cannot use a clickable method but instead I have some code that activates when the data is received from the sensor. The code then analyzes the data and decides which of several images to display. The program then needs to update the actionbar image. This is the part I need your help on. I think I should use onPrepareOptionsMenu to update the image. However, I cannot seem to get the code correct to call onPrepareOptionsMenu. In particular, onPrepareOptions uses parameters (Menu menu). I cannot seem to specify the second menu properly as it always gives an error. The code below gives:
"required android.view.Menu found int". If I initialize menu with null I get a null reference error. Any suggestions how to correct my code or maybe do something totally different to be able to update the image? Thanks. Below is my java code.
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear(); // Clear the menu first
Log.d(TAG, " Before inflation");
getMenuInflater().inflate(R.menu.gatt_services, menu);
Log.d(TAG, "Before the findItem");
menu.findItem(R.id.menu_batlevel).setIcon(R.drawable.low25);
return super.onPrepareOptionsMenu(menu);
}
Code to call the onPrepareOptionsMenu with:
...
else if (dataType == 2.0) {
Menu menu = (R.menu.gatt_services);
getMenuInflater().inflate(R.menu.gatt_services, menu);
onPrepareOptionsMenu(Menu menu);
...
XML code for the action bar. The image I am trying to change is item id/menu_batlevel:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/menu_refresh"
android:checkable="false"
android:orderInCategory="1"
android:showAsAction="ifRoom"/>
<item android:id="#+id/menu_batlevel"
android:checkable="false"
android:icon="#drawable/discharged"
android:title="BatLev"
android:orderInCategory="2"
android:showAsAction="ifRoom"/>
<item android:id="#+id/menu_connect"
android:title="#string/menu_connect"
android:orderInCategory="100"
android:showAsAction="ifRoom|withText"/>
<item android:id="#+id/menu_disconnect"
android:title="#string/menu_disconnect"
android:orderInCategory="101"
android:showAsAction="ifRoom|withText"/>
</menu>
My solution is shown below. I put the if statements that update the image into the onCreateOptionsMenu:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.d(TAG, "onCreateOptions Before inflation");
getMenuInflater().inflate(R.menu.gatt_services, menu);
...
if (dataType == 2.0){
if (bat_level < 10) {
MenuItem batItem = menu.findItem(R.id.menu_batlevel);
batItem.setIcon(R.drawable.discharged);
}
...
I added a class:
class VersionHelper
{
static void refreshActionBarMenu(Activity activity)
{
activity.invalidateOptionsMenu();
}
}
I call the class from my program:
...
else if (dataType == 2.0) {
VersionHelper.refreshActionBarMenu(DeviceControlActivity.this);
...
The above code is working. As you can tell, I am new to java so if you see a problem with this code or have a better method, please let me know.
If you want to change the image on an existing menu item, you can save a reference to the menu item when it's created, something like this:
private MenuItem photoMenuItem;
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
inflater.inflate(R.menu.menu_end_details, menu);
// find the photo menu and save it
photoMenuItem = menu.findItem(R.id.photoMenuItem);
}
Then when it's time to update the menu item, just call setIcon:
if (photoMenuItem != null)
{
photoMenuItem.setIcon(R.drawable.camera_active);
}
If you want to decide whether or not to show a particular menu item, you can call setVisible instead of setIcon on the items whose presence may change.
Related
Here is the runtime exception
java.lang.ClassCastException: android.support.v7.widget.ShareActionProvider cannot be cast to android.view.View
I have tried many different ways of doing this but I know it has to do with the ShareActionProvider I can add links to sites where there are several ways of doing this but it is not working here is the entire code
And by "this" I mean instantiating the ShareActionProvider
Please to not set this as duplicate it is not I have looked on SO and none of them have helped ... Sod to say
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// TODO: Implement this method
MenuInflater inflator = getMenuInflater();
inflator.inflate(R.menu.sidebar_menu, menu);
SubMenu subMenu = menu.addSubMenu("Themes");
subMenu.add(0 , blue , 0 , "Blue");
subMenu.add(0, pink , 1, "Pink");
items = subMenu.getItem().getItemId();
// tool bar menu
MenuItem mi = menu.findItem(R.id.searchable);
mi.setIcon(android.R.drawable.ic_search_category_default);
SearchView searchView = (SearchView)MenuItemCompat.getActionView(mi);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
sap = (ShareActionProvider) MenuItemCompat.getActionProvider(menu.findItem(R.id.share));
Intent intentShare = new Intent(Intent.ACTION_SEND);
intentShare.setType("text/plain");
intentShare.putExtra(Intent.EXTRA_SUBJECT ,"Subject here");
intentShare.putExtra(Intent.EXTRA_TEXT , "Here is the share content body");
startActivity(Intent.createChooser(intentShare,"Share via"));
sap.setShareIntent(intentShare);
MenuItemCompat.OnActionExpandListener el = new MenuItemCompat.OnActionExpandListener(){
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when action item collapses
return true; // Return true to collapse action view
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Do something when expanded
return true; // Return true to expand action view
}};
MenuItem actionMenuItem = menu.findItem(R.id.searchable);
// Assign the listener to that action item
MenuItemCompat.setOnActionExpandListener(actionMenuItem,el);
return super.onCreateOptionsMenu(menu);
}
Can anyone help please ! I think I have been clear enough with this issue I am having if needed I can post up the menu.XML file along with appmanifest.XML along with the other XML files which I see no reason to put up ... Thank you
Here is the menu.xml as requested
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item
android:id="#+id/searchable"
android:title="#string/tbmenuitem_search"
myapp:showAsAction="ifRoom|collapseActionView"
myapp:actionViewClass="android.support.v7.widget.SearchView"
/>
<item
android:id="#+id/share"
android:showAsAction="ifRoom"
android:title="#string/sharetitle"
myapp:actionViewClass="android.support.v7.widget.ShareActionProvider"
/>
<item
android:id="#+id/playlist"
android:title="Play lists"
/>
<item
android:id="#+id/muteoption"
android:title="Mute"
/>
<item
android:id="#+id/unmuteoption"
android:title="UnMute"
/>
<item
android:id="#+id/sharewidget"
android:title="Share"
/>
[Edited] my XML file actionViewClass should have been actionViewProvider hence the run time error .
I want to be able to display the number of the week in the action bar inside a picture. My first attempt was to display the title in the icon but it shows either title or icon not both at the same time. Next I tried to create different pictures that could been used for icon containing the number of the week. But i can't find a way to change the icon.
Anybody have an idea what i can do?
This is the code for the menu
<item android:id="#+id/action_week"
android:title="p"
android:showAsAction="always"
android:icon="#drawable/vecka0"/>
<item
android:id="#+id/menu_overflow"
android:icon="#drawable/menu_large"
android:showAsAction="always"
android:title="#string/Vmeny">
<menu>
<item android:id="#+id/action_confirm"
android:title="#string/confirm_text"
android:showAsAction="ifRoom" />
<item android:id="#+id/action_switch_company"
android:title="#string/Vswitch_company"
android:showAsAction="never"/>
<item android:id="#+id/action_logout"
android:title="#string/logout_text"
android:showAsAction="ifRoom"/>
</menu>
</item>
And here is the menu that i want
Shows icon not text
For this in your item tag mention.
<item android:id="#+id/action_week"
android:title="p"
android:showAsAction="always|withText" //this would show icon and text both at atime
android:icon="#drawable/vecka0"/>
Changing Icons Dynamicaly
you need to have reference to menu at the time of creation of menu first.
private Menu mMenu;
#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_activity, menu);
// Save the menu reference
mMenu = menu;
return super.onCreateOptionsMenu(menu);
}
// For example - Call when you need to change icon
private void setActionIcon(boolean showWithBadge){
MenuItem item = mMenu.findItem(R.id.ITEM_ID);
if(mMenu != null){
if(showWithBadge){
item.setIcon(R.drawable.IC_WITH_BADGE);
}
else {
item.setIcon(R.drawable.IC_WITHOUT_BADGE);
}
}
}
maybe you could create a global Menu variable (if you are going to use it later if not make it local) and initialize it on the onCreateOptionsMenu().
private Menu menu;
Inside the onCreateOptionsMenu():
this.memu = menu;
And then get the item you want of your menu and change it:
menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.ic_launcher));
I am trying to get the View of the MenuItem.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
View miView = MenuItemCompat.getActionView(item);
if (miView == null) {
Log.e(X, "mView is null");
}
}
but everytime miView is null.
Here's my onCreateOptionsMenu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, R.string.Foo);
return true;
}
I know that MenuItemCompat returns null because the created Menu is not a from support library, so the MenuItem can't be handled by the MenuItemCompat class, isn't?
1) I am looking for some method like onCreateOptionsMenuCompat, is there any method like that?
2) How can i get ActionView from MenuItemCompat class?
and What am i doing wrong ?
PS: my project's minSdkVersion is 9
To get an ActionView from a menu item, you will need to set an ActionView on it first. Normal menu items do not come with ActionViews. ActionViews are used when you need to do something extra in your menu (outside of a normal icon and/or text).
Why are you trying to get a View from the menu item? What are you trying to do with your menu item?
I'm trying to avoid having fullscreen keyboard editing on landscape in order to access to the suggestions.
I already read a lot of threads explaining that I have to add EditorInfo flags like flagNoFullscreen and/or flagNoExtractUi.
I added them programmatically but not really helpful.
Is there a way to figure this out?
It took me a while to figure this one out, but it's actually quite simple.
Initially I created a custom class that extended the SearchView class, and used a onCreateInputConnection() override, however I couldn't get it working that way.
I eventually got it working in a much more simple way, with just two added lines of code.
You just need to call search.getImeOptions() to get the current configuration, and then "or" the result with EditorInfo.IME_FLAG_NO_EXTRACT_UI with a call to setImeOptions():
Java:
search.setImeOptions(options|EditorInfo.IME_FLAG_NO_EXTRACT_UI);
Kotlin:
search.setImeOptions(search.imeOptions or EditorInfo.IME_FLAG_NO_EXTRACT_UI)
If you don't "or" with the existing options, then you don't get the "Search" completion button in the lower right, you just get a "Done" button instead.
Here is the full onCreateOptionsMenu() override I used to test (I used a SearchView in the xml, but this solution should work for you even if you're not inflating your SearchView from xml):
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView search = (SearchView) menu.findItem(R.id.action_search).getActionView();
SearchableInfo si = manager.getSearchableInfo(getComponentName());
//Here is where the magic happens:
int options = search.getImeOptions();
search.setImeOptions(options|EditorInfo.IME_FLAG_NO_EXTRACT_UI);
//!!!!!!!!!!!
search.setSearchableInfo(si);
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String query) {
return true;
}
});
return true;
}
Here is the xml I used for the SearchView in menu_main.xml:
<item android:id="#+id/action_search"
android:title="Search"
android:icon="#android:drawable/ic_menu_search"
app:showAsAction="always"
app:actionViewClass="android.support.v7.widget.SearchView"
/>
Result without the call to setImeOptions():
Result with the call to setImeOptions():
Another alternative to the code is to add the property in the searchView xml, it is useful for APIs less than 16:
<SearchView
android:imeOptions="flagNoExtractUi" />
Same idea as above written but without SearchView, only using searchable XML
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
...
android:imeOptions="actionSearch|flagNoExtractUi"
...
</searchable>
I know this is really basic but it is a error that I cannot find a solution to.
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/graphics/CameraPreview.html
I have 2 errors and I dont know what Im doning wrong.
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate our menu which can gather user input for switching camera
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.camera_menu, menu);
return true;
}
Im getting an error at "menu" in "R.menue..."
error 2:
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.switch_cam:
// check for availability of multiple cameras
if (numberOfCameras == 1) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
/**builder.setMessage(this.getString(R.string.camera_alert))
.setNeutralButton("Close", null);*/
AlertDialog alert = builder.create();
alert.show();
return true;
}
Im getting an error on "id" in "case R.id..."
Thanks
First, do you have : <uses-permission android:name="android.permission.CAMERA" />in your AndroidManifest.xml ?
You can try to check a full Camera preview here for Android : Camera Preview Android
Another good website with source files : Using Camera API with SourceFile
You most likely just copied the source file you linked above into your project. You also have to add res/menu/camera_menu.xml. This defines the options menu that comes up when you press the menu button. See the menu doc for more information how that works if you're interested.
If you don't do that the tools notice that you miss a file that you reference in code but that's not actually there, which results the first error. The second error is also caused by this in an indirect way. The missing ID is also created within the menu file.