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>
Related
I'm struggling to use ImageView as a button that I need when I click it should display items, like when we click a spinner the same procedure.
final View imageButton = findViewById(R.id.imageButton);
imageButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
// display a list of suggestions !
}
});
I will be thankful if there is anyone who gonna help me to solve this problem.
First you create your menu of items you want to show like this
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/first"
android:title="First Menu Item"/>
<item
android:id="#+id/second"
android:title="Second Menu Item"/>
<item
android:id="#+id/third"
android:title="Third Menu Item"/>
</menu>
Then in your Activity you create a PopupMenu
PopupMenu pm = new PopupMenu(MainActivity.this, pBtn);
pm.getMenuInflater().inflate(R.menu.popup_menu, pm.getMenu());
pm.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.first:
Toast.makeText(MainActivity.this, "Clicked First Menu Item", Toast.LENGTH_SHORT).show();
return true;
case R.id.second:
Toast.makeText(MainActivity.this, "Clicked Second Menu Item", Toast.LENGTH_SHORT).show();
return true;
case R.id.third:
Toast.makeText(MainActivity.this, "Clicked Third Menu Item", Toast.LENGTH_SHORT).show();
return true;
}
return true;
}
});
pm.show();
Finally you call this popup menu in your click listener
EDIT:
Create an ArrayList of String for example
ArrayList<String> popupItems = new ArrayList<String>();
Fill your arraylist with your data
Then you initialize your popupmenu with this array list
popupMenu = new PopupMenu(this, imageButton);
Loop through your array add values to the popupmenu menu
for (int i =0; i < popupItems.size(); i++)
popupMenu.getMenu().add(Menu.NONE, 1, Menu.NONE, popupItems.get(i))
You can show the items in dialog, when you click on image view show the dialog
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
I want to be able to respond to a click event on a disabled switch, is that possible?
I have a switch that is not enabled until the user fills in some information, so it looks like this:
I want to prompt the user to fill out the information if they click on the disabled switch with a dialog, like so:
mySwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!userInfo.isFilled){
new AlertDialog.Builder(MainActivity.this)
.setTitle("Fill out info first!")
.setMessage("You must first fill out info before turning on this featurel")
.setNeutralButton("Okay", null)
.show();
}
}
});
However, the onClick() is not triggered when I click on the disabled switch, so how do I get when the user clicks on it?
You could place a transparent View on top of the Switch and toggle its enabled state opposite the Switch, and show the message when this overlaid View is clicked.
From the View.java source code,
public boolean dispatchTouchEvent(MotionEvent event) {
// If the event should be handled by accessibility focus first.
if (event.isTargetAccessibilityFocus()) {
// We don't have focus or no virtual descendant has it, do not handle the event.
if (!isAccessibilityFocusedViewOrHost()) {
return false;
}
// We have focus and got the event, then use normal event dispatch.
event.setTargetAccessibilityFocus(false);
}
boolean result = false;
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(event, 0);
}
final int actionMasked = event.getActionMasked();
if (actionMasked == MotionEvent.ACTION_DOWN) {
// Defensive cleanup for new gesture
stopNestedScroll();
}
if (onFilterTouchEventForSecurity(event)) {
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
if (!result && onTouchEvent(event)) {
result = true;
}
}
if (!result && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
}
// Clean up after nested scrolls if this is the end of a gesture;
// also cancel it if we tried an ACTION_DOWN but we didn't want the rest
// of the gesture.
if (actionMasked == MotionEvent.ACTION_UP ||
actionMasked == MotionEvent.ACTION_CANCEL ||
(actionMasked == MotionEvent.ACTION_DOWN && !result)) {
stopNestedScroll();
}
return result;
}
the enabled flag ensures the UnhandledEvents are consumed however not passed along to the listeners,thereby bypassing all your possible code.So it is not possible to listen to events on a disabled view.
That said, your options are,
Change the style to mimic that of a disabled view as mentioned here,and then add your required functionality.
Add a overlay invisible view to perform your required functionality which you can set to Gone once the view should be enabled.
Use something apart from enabled,(you could setClickable(false) and consume touch events)
You can set onTouchListener and react to boolean (e.g isToggleEnable) reference with respect to the user's previous actions:
mySwitch.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(!isToggleEnable){
//Taost here
}
//If isToggleEnable = false on return OnClickListener won't be called
return isToggleEnable;
}
});
When it is disabled, setEnabled(false), these listeners won't work.
Try this way: don't disable it, use the setOnCheckedChangeListener and check against your is-entry-filled in there:
use setOnCheckedChangeListener
switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!isEntryFilled) {
buttonView.setChecked(false);
// your alert dialog
} else {
}
}
});
this will re-check it back to off and pop your alert, until isEntryFilled is met.
EDIT
OR instead of setEnabled(false), use setClickable(false) or android:clickable="false" since docs say setClickable() is tied to click-events.
and instead of OnClickListener, try OnTouchListener. It will register your on-down-touch (and ignore your on-up-touch), since a click consists of down+up.
switch.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (!isEntryFilled) {
buttonView.setChecked(false);
// your alert dialog
}
return false;
}
});
then somewhere else, where you check for isEntryFilled, reactivate your switch with switch.setClickable(true)
Try setting setFocusable(false) and setEnabled(true) on your switch. That way, click events will be fired while the switch still being "disabled". Taken from this answer.
mySwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isClick()){
//Your Valid Code
}else{
//Make our switch to false
new AlertDialog.Builder(MainActivity.this)
.setTitle("Fill out info first!")
.setMessage("You must first fill out info before turning on this featurel")
.setNeutralButton("Okay", null)
.show();
}
}
});
public Boolean isClick(){
//check condition that user fill details or not
//if yes then return true
// else return false
}
Let the Parent View intercept ClickEvents or TouchEvents, when its detected check if the receiving View is disabled, and do what you have to do.
Edit
"it doesn't work when disabled?"
try these codes, Im use LinearLayout for easy aligment. but overall it should give you an example
this is a full example
XML
<FrameLayout 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="70dp"
android:background="#273746">
<FrameLayout
android:layout_width="match_parent"
android:id="#+id/ass"
android:background="#drawable/abc_popup_background_mtrl_mult"
android:layout_height="match_parent">
</FrameLayout>
MainActivity onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_entry_screen);
FrameLayout fl = (FrameLayout)findViewById(R.id.ass);
Test t = new Test(this);
FrameLayout.LayoutParams lp = (LayoutParams) fl.getLayoutParams();
lp.height = LayoutParams.MATCH_PARENT;
lp.width = LayoutParams.MATCH_PARENT;
t.setOrientation(LinearLayout.VERTICAL);
t.setLayoutParams(lp);
fl.addView(t);
t.setBackgroundColor(Color.YELLOW);
Button b = new Button(this);
b.setText("patricia");
t.addView(b);
b = new Button(this);
b.setText("monica");
t.addView(b);
b = new Button(this);
b.setText("rebecca");
t.addView(b);
}
Test.java
public class Test extends LinearLayout {
public Test(Context context) {
super(context);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
StringBuilder sb = new StringBuilder();
sb.append("intercept \n\r");
int x = (int)event.getX(),
y= (int)event.getY();
for(int i =0; i< getChildCount(); i++){
int[] pos = new int[]{getChildAt(i).getLeft(),getChildAt(i).getTop(),
getChildAt(i).getMeasuredWidth(),
getChildAt(i).getMeasuredHeight()};
sb.append(getChildAt(i).getLeft()+", ");
sb.append(getChildAt(i).getTop()+", ");
sb.append(getChildAt(i).getMeasuredWidth()+", ");
sb.append(getChildAt(i).getMeasuredHeight());
sb.append("\n\r");
sb.append(isInBounds(pos, x, y));
sb.append("\n\r");
}
sb.append("x is ");
sb.append(x);
sb.append("y is ");
sb.append(y);
Toast.makeText(getContext(),sb.toString() , Toast.LENGTH_LONG).show();
return super.onInterceptTouchEvent(event);
}
private boolean isInBounds(int[] dimen, int x, int y){
return ((x >= dimen[0] && x < (dimen[0] + dimen[2]))
&& (y >= dimen[1] && y < (dimen[1] + dimen[3])));
}
}
Now The one you click will check out to be true, that is the child, now when it checks out to be true you can do something like this
View v = getchildAt(pos);
//its the one that is tapped or clicked
if(!v.isEnabled()){
//this is the guy you want now, do what you want to do
for click event i am not try this, but you could just do View.performClick() or put your Dialog in the ViewGroup class and call it
actually you could use the View..getClipBounds() to save yourself from int array
Set the disable switches on click listener to change the listeners of the other switches. For example:
Switch s = (Switch) findViewById(R.id.SwitchID);
if (s != null) {
s.setOnCheckedChangeListener(this);
}
/* ... */
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Toast.makeText(this, "The Switch is " + (isChecked ? "on" : "off"),
Toast.LENGTH_SHORT).show();
if(isChecked) {
//do stuff when Switch is ON
//this is where you set your normal state OnClickListner
} else {
mySwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!userInfo.isFilled){
new AlertDialog.Builder(MainActivity.this)
.setTitle("Fill out info first!")
.setMessage("You must first fill out info before turning on this featurel")
.setNeutralButton("Okay", null)
.show();
}
}
});
}
}
I'm guessing you've disabled the switch using switch.setEnabled(false). If so, the onclick event will not trigger. If you still want to handle a click action when the switch is disabled, you can use .setOnTouchListener()...
You're best bet however would be to use .setOnCheckedChangeListener() and keeping the switch enabled. Basically when onCheckChanged() gets called, you can popup your dialog if the switch value is on and when the user click ok, you default the switch back to off.
mSwitched.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
if (checked && !userInfo.isFilled){
new AlertDialog.Builder(Activity.this)
.setTitle("Fill out info first!")
.setMessage("You must first fill out info before turning on this featurel")
.setNeutralButton("Okay", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
mSwitched.setChecked(false);
}
})
.show();
}
}
});
You can do this in a different way,Give a root layout to toggle button with same width and height of toggle button
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<!--Root layout to toggle button with same height and width
of toggle button-->
<LinearLayout
android:layout_width="wrap_content"
android:id="#+id/linear"
android:layout_height="wrap_content">
<ToggleButton
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
/>
</LinearLayout>
</RelativeLayout>
When you disable the button,make the button as not focasable and clickable .Then os will handover touch functionality to rootlayout.In the root layout click listner we can write the click logic when the button is not enabled
public class MainActivity extends AppCompatActivity {
ToggleButton button;
LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button= (ToggleButton) findViewById(R.id.button);
linearLayout= (LinearLayout) findViewById(R.id.linear);
//disabling button
button.setEnabled(false);
button.setClickable(false);
button.setFocusableInTouchMode(false);
button.setFocusable(false);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//write the logic here which will execute when button is enabled
}
});
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//write the logic here which will execute when button is disabled
}
});
}
}
When you enable the button,make button to clickable and focausable.
//enabling button
button.setEnabled(true);
button.setClickable(true);
button.setFocusableInTouchMode(true);
button.setFocusable(true);
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>
Im working on a simple music player for my intro to Android apps class. I want to be able to add songs to a playlist listed in my context menu. When I click on my addtoplaylist contextmenuitem I want my popup menu to appear. How do I call my popup menu? Also if you have some suggestions on how to populate my popup menu, rather than my for loop, that would be cool too.
I have a contextmenu listener that kind of looks like this.
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.share:
shareIt();
return true;
case R.id.Store:
musicStore();
return true;
case R.id.addtoplaylist:
// open popup menu
return true;
case R.id.snippet:
snippet(tem1);
return true;
default:
return super.onContextItemSelected(item);
}
}
And i have a popup menu that kind of looks like this.
public void showPopup(View v) {
int i = view.getPlaylists().size();
ArrayList<String> playlist = view.getPlaylists();
PopupMenu popup = new PopupMenu(this, v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.popup_menu, popup.getMenu());
for(int k = 0; k > i;k++){
popup.getMenu().add(playlist.get(k));
}
popup.show();
}
As you can see here PopupMenu
V is just an anchor, so you can pass for instance the ListView which contains your item
Or if you really want the popupmenu to be anchored to the item have a look here
You get your target view like this.
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
View v = info.targetView;
So after call
showPopUp(v);
For your loop, I don't see a far better solution.
the accepted question is fine, but for the for loop part you could use an iterator :)
for (String song : playlist) {
popup.getMenu().add(song);
}