I have a microphone button in my options menu. When I click it, I want it to display an alternate image( red microphone ).
But it's not working. Fails with ResourcesNotFoundException. The images(png's) are definitely in the appropriate res folders.
Here's my code:
In activity:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.ic_action_microphone :
MenuItem rec = m_menu.findItem(R.id.ic_action_microphone);
if (m_start) {
rec.setIcon(R.id.ic_action_microphone_active);
startRecording();
} else {
rec.setIcon(R.id.ic_action_microphone);
stopRecording();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
In xml file:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="#+id/ic_action_microphone"
android:icon="#drawable/ic_action_microphone"
android:title="#string/action_microphone"
android:showAsAction="always"/>
<item android:id="#+id/ic_action_microphone_active"
android:icon="#drawable/ic_action_microphone_active"
android:title="#string/action_microphone"/>
</menu>
What am I doing wrong?
Thanks in advance
Try this instead: Set icon by providing images from the drawable resource folders.
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
case R.id.ic_action_microphone :
MenuItem rec = m_menu.findItem(R.id.ic_action_microphone);
if (m_start) {
rec.setIcon(R.drawable.ic_action_microphone_active);
startRecording();
} else {
rec.setIcon(R.drawable.ic_action_microphone);
stopRecording();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
You probably want to set resource from drawable and not ids. I hope this helps you.
Related
I'm new to android development and kinda to Java as well.
I'm learning how to add buttons to actionbar - everything is working, but I don't understand few things.
//Showing small icons at actionbar
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
menuItem = menu.findItem(R.id.recBin); // Finds the button in Actionbar and gets the ID
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.recBin: // Actions for delete button
dbHandler.remove(getID());
displayTaskList();
menuItem.setVisible(false); // Hide the button
break;
case R.id.editBtn: // Actions for editbutton
Toast.makeText(MainActivity.this,
"EDIT", Toast.LENGTH_LONG).show();
break;
case R.id.closeBtn:
Toast.makeText(MainActivity.this,
"CLOSE", Toast.LENGTH_LONG).show();
break;
default:
break;
}
return true;
}
This line: menuItem = menu.findItem(R.id.recBin); Is for what exactly? I took it off and my app crashed, so I understand that it's mandatory. What I don't understand is what icons ID should I put at bold space? It has to be from "menu" right, but does it matter which id I take? For instance, if I took R.id.closeBtn instead of recBin? As long as it's an id from menu, it works?
P.S. I hope this isn't a terrible question [probably is] and I'm sorry if so.
Solution:
Turns out you can simply get ID's. Stupid and simple.
private MenuItem item1, item2, item3;
//Showing small icons at actionbar
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
item1 = menu.findItem(R.id.recBin); // Rec button
item2 = menu.findItem(R.id.editBtn); // Edit button
item3 = menu.findItem(R.id.closeBtn); // Close button
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.recBin: // Actions for delete button
dbHandler.remove(getID());
displayTaskList();
item1.setVisible(false); item2.setVisible(false); item3.setVisible(false); // Hiding all buttons
break;
case R.id.editBtn: // Actions for editbutton
item1.setVisible(false); item2.setVisible(false); item3.setVisible(false); // Hiding all buttons
break;
case R.id.closeBtn:
item1.setVisible(false); item2.setVisible(false); item3.setVisible(false); // Hiding all buttons
break;
default:
break;
}
return true;
}
It's a reference to MenuItem, but it would be easier if you do:
case R.id.recBin: // Actions for delete button
dbHandler.remove(getID());
displayTaskList();
item.setVisible(false); // Hide the button
break;
You can safely remove the reference afterwards
I want to create a simple drop down list/listview like in below image. It should generate programmatically without using any xml layout.
NOTE : I am not using a spinner in here . Also I want to open it when I click on the ImageView next to the Switch.
I have no idea about this .
Have any ideas ?
not perfect, but it works ;)
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(MainActivity.this, button);
popupMenu.getMenu().add("Edit");
popupMenu.getMenu().add("Delete");
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getTitle().toString()) {
case "Edit" :
//execute "edit" action
break;
case "Delete" :
//execute "delete" action
break;
}
return false;
}
});
popupMenu.show();
}
});
Just try to check and implement it
PopupMenu overflowPopupMenu = new PopupMenu(getContext(), finalOverflow);
overflowPopupMenu.getMenuInflater().inflate(R.menu.popup_overflow_options, overflowPopupMenu.getMenu());
overflowPopupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(android.view.MenuItem item) {
switch (item.getItemId()) {
case R.id.edit:
break;
case R.id.delete:
break;
}
return true;
}
});
overflowPopupMenu.show();
popup_overflow_options.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
>
<item
android:id="#+id/edit"
android:title="#string/edit"/>
<item
android:id="#+id/delete"
android:title="#string/delete"/>
</menu>
I use PopupMenu's for this. See also this guide. The guide explains how to use the PopupMenu with an xml menu resource.
In your case you would attach a click listener to the ImageView. That listener would then create a PopupMenu using the ImageView as an anchor. Like this: PopupMenu popup = new PopupMenu(imageView.getContext(), imageView);
At this point since you need dynamic menu items you have the following options:
You can call PopopMenu.getMenu() and manually populate it with MenuItems
You can create an xml menu resource and then adjust/hide ones that need to be changed
I am relatively new to android development and have been trying to learn about MenuItem's but haven't had much success. I am having trouble calling a method when a menuitem is clicked on. Here is my code:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
String selectedMenuIdString = (String) item.getTitleCondensed();
if (selectedMenuIdString.equals("about")) {
doThis(item);
return true;
}
return true;
}
public void doThis(MenuItem item) {
Toast.makeText(this, "Hello World", Toast.LENGTH_LONG).show();
}
It worked once a few days back but it wont now and I have no idea why. Could anyone help?
<item
android:id="#+id/search"
android:orderInCategory="100"
android:title="#string/search"
android:titleCondensed="search"
/>
<item
android:id="#+id/products"
android:orderInCategory="100"
android:title="#string/products"/>
<item
android:id="#+id/contact_us"
android:orderInCategory="100"
android:title="#string/contactus"/>
<item
android:id="#+id/about"
android:orderInCategory="100"
android:title="#string/about"/>
And my strings:
<string name="search">Search</string>
<string name="products">Products</string>
<string name="contactus">Contact Us</string>
<string name="about">About</string>
Do it this way, it's much easier:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getId(); // Retrieve the id of the selected menu item
switch(id) {
case R.id.about: // "#+id/about" is the id of your menu item (menu layout)
doThis(item);
return true;
break;
case ...
}
return super.onOptionsItemSelected(item);
}
No listeners, no extra complexity.
Always compare the items id not the title or something else, like in the other answer.
An other nice way to do it: Try handling the click events through an OnMenuItemClickListener, in the onPrepareOptionsMenu function. Sample code below:
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem prefs = menu.findItem(R.id.prefs); // your item identifier
prefs.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
doThis();
return false;
}
});
}
You say
String selectedMenuIdString = (String) item.getTitleCondensed();
if (selectedMenuIdString.equals("about")) {
and the about menu item as it seems here does not have a condensedTitle
<item
android:id="#+id/about"
android:orderInCategory="100"
android:title="#string/about"/>
So modify your code like:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.about:{
//do something here
return true;
break;
}
case R.id.search:{
//do something here
return true;
break;
}
case R.id.contact_us:{
//do something here
return true;
break;
}
case R.id.products:{
//do something here
return true;
break;
}
}
return super.onOptionsItemSelected(item);
}
I have an app about studying sacred Indian texts usually consisting of a verse and a commentary to this verse.
To open it up I use DisplayText activity which has an ActionBar popping up when user selects some text from either a verse or its commentary.
My problem is that it works inconsistently - on my Samsung Galaxy Note 2 it works OK, but on sony xperia Z2 once I try to touch the action button it exits the action bar and nothing happens.
Samsung's Android version is 4.4.2 and Sony's version 4.4.4
Please check out this very short video for Sony device and also how it works for samsung device
Please note that there are no error messages being shown in the LogCat view.
I would appreciate any suggestions on how I could possibly fix this problem
Also any ways to get a work around would be much appreciated as well.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Log.v("DEBUG", "DisplaTEXT onCreate - Starting Activity");
try
{
m_context=this;
mtxtTransl2View.setCustomSelectionActionModeCallback(new CustomTextSelectCallback(mtxtTransl2View, false));
mtxtComment.setCustomSelectionActionModeCallback(new CustomTextSelectCallback(mtxtComment, true));
}
catch(Exception e)
{
e.printStackTrace();
}
}
#SuppressLint("NewApi")
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
class CustomTextSelectCallback implements ActionMode.Callback {
public CustomTextSelectCallback(TextView tv, boolean b) {
mTextView=tv;
mbPurport=b;
}
//flag that selection is made in the purport, otherwise it is in shloka or translit
private TextView mTextView;
private boolean mbPurport;
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
//Log.d(TAG, "onCreateActionMode");
//if(mbPurport)
{
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.text_selection_menu, menu);
MenuItem item = menu.findItem(R.id.cab_menu_fb);
ShareActionProvider actionProvider = (ShareActionProvider)item.getActionProvider();
actionProvider.setShareIntent(createShareIntent());
actionProvider.setOnShareTargetSelectedListener(new OnShareTargetSelectedListener(){
public boolean onShareTargetSelected(ShareActionProvider source, Intent intent)
{
try
{
getShareSubject("Share Subject","Please describe why would you like to share this (optional):");
}
catch(Throwable e)
{
String err="Error11: " + e.getMessage();
Toast.makeText(getApplicationContext(), err, Toast.LENGTH_LONG).show();
}
if(mShareSubj.equals(SUBJ_CANCEL)) return false;
int start = mTextView.getSelectionStart();
int end = mTextView.getSelectionEnd();
int tvID=mTextView.getId();
String sPlaceType = (tvID==R.id.textTransl2) ? "t":"p";
mTextURL=mTextURL+"?t="+sPlaceType+"&s="+start+"&e="+end;
mANText=mTextView.getText().subSequence(start, end).toString();
if ("com.facebook.katana".equals(intent.getComponent().getPackageName()) )
{
//mfacebooksharer.shareStatus(subject, text);
// Toast.makeText(this, "Facebook sharing", Toast.LENGTH_LONG).show();
shareOnFacebook();
return false;
}
else
{
if(!MyApp.mC.hasFlag(Cookies.FL_Sharing, m_context))
return true;
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(android.content.Intent.EXTRA_TEXT, getShareBody(intent));
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, mShareSubj);
getApplicationContext().startActivity(intent);
return true;
}
}
});
}
return true;
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
//Log.d(TAG, String.format("onActionItemClicked item=%s/%d", item.toString(), item.getItemId()));
int start = mTextView.getSelectionStart();
int end = mTextView.getSelectionEnd();
long note_id=-1;
mANPlace=UserDataSQLHelper.NOTE_PLACE_TEXT;
mANText=mTextView.getText().subSequence(start, end).toString();
if(mbPurport)
mANPlace=UserDataSQLHelper.NOTE_PLACE_COMM;
mANStartPos=start;
mANEndPos=end;
mScrollPos = mScrollT.getScrollY();
switch(item.getItemId()) {
case R.id.cab_menu_fav:
if(!MyApp.mC.hasFlag(Cookies.FL_TextHighlight, m_context)) return false;
note_id=MyApp.mUserDB.addNote(m_dbtype, m_dblang, mCurrBookID, mCurrSong, mCurrChapterNum, mCurrTextNum, mRowID, UserDataSQLHelper.NOTE_TYPE_HIGHL, mANPlace, start, end, mScrollPos,
mANText, "", "");
break;
case R.id.cab_menu_comment:
if(!MyApp.mC.hasFlag(Cookies.FL_TextHighlightAddCommentsQuestions, m_context)) return false;
Intent intent = new Intent(getApplicationContext(), NoteEditor.class);
intent.putExtra("NOTEEDIT_ACTION", NoteEditor.ACTION_ADD);
intent.putExtra("NOTEEDIT_TITLE", "Add Question or Note");
startActivityForResult(intent, SUBACT_ADDEDITNOTE);
break;
}
if (note_id!=-1){
ReloadText();
AddTags(note_id);
}
return false;
}
public void onDestroyActionMode(ActionMode mode) {
}
}
Text selection menu xml code is here:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/cab_menu_fb"
android:orderInCategory="10"
android:showAsAction="always"
android:icon="#drawable/cab_facebook"
android:actionProviderClass="android.widget.ShareActionProvider"
android:title="#string/cab_menu_fb"/>
<item
android:id="#+id/cab_menu_fav"
android:orderInCategory="20"
android:showAsAction="ifRoom"
android:icon="#drawable/cab_highl"
android:title="#string/cab_menu_fav"/>
<item
android:id="#+id/cab_menu_comment"
android:orderInCategory="30"
android:showAsAction="ifRoom"
android:icon="#drawable/cab_comment"
android:title="#string/cab_menu_comment"/>
</menu>
I have been trying to figure out why my boolean is not changing when I press the button, when I changed it manually it worked, but it doesn't do any thing. I have tried to follow tutorials to the word but they don't work. Can anybody point out where I am going wrong?
public boolean onOptionsItemSelected(MenuItem menu)
{
MenuItem freeze = (MenuItem)findViewById(R.id.freeze);
// Handle item selection
switch (menu.getItemId()) {
case R.id.freeze:
if (freze == false){
freze = true;
} else {
freze = false;
}
return true;
case R.id.toggleVolCount:
if (toggleVol == true){
toggleVol = false;
} else {
toggleVol = true;
}
return true;
default: return super.onOptionsItemSelected(menu);
}
Thanks for all your help, when I tried the code that was suggested and it didn't work I went back and changed the menu. Previously I had made a button with an onClick to create the menu, when created the icon with code the code that I had previously written worked fine. Hope this helps someone other than me so I don't feel like so much of an idiot.}
In res folder create one folder menu like drawable
Create new xml file optionmenu.xml in that folder.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/menuitem"
android:title="Prefs">
</item>
<item android:id="#+id/menuitem1"
android:title="Prefs1">
</item>
</menu>
In onCreate method write this code....
setOptionMenu(R.menu.optionmenu);
and in overide method of Menu write this code.....
#Override
public boolean onOptionsItemSelected(MenuItem menu) {
switch (menu.getItemId()) {
case R.id.menuitem:
startActivity(new Intent(this, Prefs.class));
break;
case R.id.menuitem1:
startActivity(new Intent(this, Prefs1.class));
break;
default:
break;
}
return true;
}