Android TextView actionbar works inconsistently - java

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>

Related

Android: MenuInflater Works Only On Emulator, Not Real Device

For some reason when the following code runs my phone won't display a popup window with the text "+ create new track", yet the same thing works if I run on an Android Studio emulator.
I can't spot the source of this issue. On my emulator popup.show() displays a window, but when i step through on my device via a debugger this line does nothing. Strangely, popup doesn't seem to be null on the device when this occurs.
How can I get the popup window to display on a real device?
private void showTrackListing(){
int writePermissionCheck = ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (writePermissionCheck != PackageManager.PERMISSION_GRANTED){
Toast.makeText(getActivity(), "Need storage write permissions", Toast.LENGTH_LONG).show();
return;
}
trackListing = getTrackNames();
PopupMenu popup = new PopupMenu(getActivity(), v);
for (int i = 0; i < trackListing.length; i++) { //add a menu item for each existing track
popup.getMenu().add(trackListing[i].getName());
}
//TODO: Add Checkable list on longpress to delete files
//TODO: potentially change popup menu to ListView for better CAB cooperation
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.new_track:
trackSelectButton.setText("...");
Toast.makeText(getActivity(), "Name your new track.", Toast.LENGTH_SHORT).show();
txtTrackName.setVisibility(txtTrackName.VISIBLE);
return true;
default:
selectedTrackName = (item.getTitle().toString());
trackSelectButton.setText(selectedTrackName);
for (int i = 0; i < trackListing.length; i++) { //add a menu item for each existing track
if (trackListing[i].getName().equals(selectedTrackName)) {
selectedTrack = trackListing[i];
AudioRecorder.setFile(selectedTrack);
}
}
return true;
}
}
});
MenuInflater popupInflater = popup.getMenuInflater();
popupInflater.inflate(R.menu.popup_menu_track_selection, popup.getMenu());
popup.show();
}
popup_menu_track_selection.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<item android:id="#+id/new_track"
android:title="+ create new track"/>
</menu>

Menu shows when it shouldn't as I set it false

I've encountered another problem with my app. When the cat dies, I hit the "results screen" (it isn't a new activity but I hide all current elements and show a new text view indicating the death cause), and I want to hide the menu items, but for some reason it's not responding to isHeDead().
Basically the problem seems to be that it doesn't see "return false" inside onCreateOptionsMenu because for some reason isHeDead() isn't working there, even though the method works everywhere else.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(fab_menu, menu);
while (!isHeDead()){
return true;
}
return false;
}
public Boolean isHeDead() {
TextView t = (TextView) findViewById(R.id.textDiedOf);
TextView textName = (TextView) findViewById(R.id.CatsTitleStats);
TextView textAge = (TextView) findViewById(R.id.CatsAgeStat);
TextView textStats1 = (TextView) findViewById(R.id.CatsStats);
TextView textStats2 = (TextView) findViewById(R.id.CatsStats2);
ImageView image = (ImageView) findViewById(R.id.imageViewCat);
if (cat.getAge() >= 20) {
textName.setVisibility(View.GONE);
textAge.setVisibility(View.GONE);
textStats1.setVisibility(View.GONE);
textStats2.setVisibility(View.GONE);
image.setVisibility(View.GONE);
t.setText("Sorry! " + getIntent().getStringExtra(KEY_NAME_EXTRA) + " died of old age.");
return true;
} else if (cat.getAnger() >= 10) {
textName.setVisibility(GONE);
textAge.setVisibility(View.GONE);
textStats1.setVisibility(View.GONE);
textStats2.setVisibility(View.GONE);
image.setVisibility(View.GONE);
t.setText("Sorry! " + getIntent().getStringExtra(KEY_NAME_EXTRA) + " died of madness.");
return true;
} ///etc...
}
User options (not sure if this has anything to do with the menu problem but still).
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
/// FEED ///
case R.id.action_feed:
int qualityRandom = (int) (Math.random() * 10);
if (qualityRandom == 5) {
cat.happy(-2);
cat.healthy(-30);
cat.angry(2);
cat.thirsty(2);
ageStat();
Stats1();
Stats2();
if (isHeDead()) {
break;
} else {
Toast.makeText(CatStatus.this, "Food was in a poor state...", Toast.LENGTH_SHORT).show();
break;
}
} else {
cat.happy(1);
cat.healthy(10);
cat.hungry(-3);
cat.angry(-1);
ageStat();
Stats1();
Stats2();
Toast.makeText(CatStatus.this, "Yummy!", Toast.LENGTH_SHORT).show();
break;
}
/// DRINK ///
case R.id.action_drink: ///etc...
When you hit results screen, if you are not going to a new activity, onCreateOptionsMenu is not being called!
You need to keep a reference to your menu:
private Menu myMenu;
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(fab_menu, menu);
this.myMenu = menu;
while (!isHeDead()){
return true;
}
return false;
}
And then, you can call inside your isHeDead() method like this:
menu.setGroupVisible(R.id.main_menu_group, false);
or:
menu.clear();
It depends on what you want.
Check this answer:
Hide/Show Action Bar Option Menu Item for different fragments
onCreateOptionsMenu is called only one time when the app launch activity

Android - MenuItem onOptionsItemSelected method not working but returning no errors

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);
}

Changing option menu button image programmatically - ResourcesNotFoundException

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.

OnActionExpandListener in menuitem not working. How to fix it?

I am developing an Android application which works from API Level 14.
I have an item in my menu file
<item
android:id="#+id/menu_search"
android:actionViewClass="android.widget.SearchView"
android:icon="#drawable/ic_action_action_search"
android:orderInCategory="3"
android:showAsAction="always"/>
I want to know the expansion and collapse of this search view,i tried this code but it is not working
#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_search, menu);
MenuItem mSearchItem = menu.findItem(R.id.menu_search);
mSearchItem.setOnActionExpandListener( new OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "onMenuItemActionExpand", 1)
.show();
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "onMenuItemActionExpand", 1)
.show();
return true;
}
});
}
}
Why am i not getting the Toasts?
I also tried code form Handling collapsible action views, it is also not working! Why these things are not working?
EDIT
I can get it work using
mSearchView.addOnLayoutChangeListener(new OnLayoutChangeListener() {
#Override
public void onLayoutChange(View v, int left, int top, int right,
int bottom, int oldLeft, int oldTop, int oldRight,
int oldBottom) {
SearchView searchView = (SearchView) v;
if (searchView.isIconified()) {
}
else{
}
}
});
But it is very slow!
Was having similar issue the solution is ( commented by the asker, I am just positing so it can get more emphasis):
add android:showAsAction="always|collapseActionView" to your menu item.
<item android:id="#+id/action_search"
android:icon="#drawable/ic_action_search"
android:title="#string/action_search"
android:showAsAction="always|collapseActionView"
android:actionViewClass="android.widget.SearchView"
android:queryHint = "#string/search_hint"/>
Toast.makeText(MainActivity.this, "onMenuItemActionExpand", 1).show();
it is recommended to either use Toast.LENGTH_SHORT or Toast.LENGTH_LONG instead of your "1".
example:
Toast.makeText(MainActivity.this, "onMenuItemActionExpand", Toast.LENGTH_SHORT).show();

Categories

Resources