Getting the selected item's position in Android popup menu class - java

I want to store some data into every item in a popup menu. All of the items are inflated programatically in a for loop based on results returned from a feed.
In the following example, I use a HashMap storedOption to store each item's data with the loop indices as keys. But I need to find a way to get the position of the selected item in onMenuItemClick so that I can retrieve the data from storedOption. Can anyone tell me how to do that? Besides the following attempt, I have also tried item.getOrder() but it always returns 0 regardless of how many items it has in the menu.
public DynamicPopUpMenu{
private Map<String,FeatureList> storedOption = new HashMap();
public void main(final Context context,List<FeatureList> featureList){
int count = 0;
PopupMenu menu = new PopupMenu(context, featureList);
for(FeatureList f:featureList) {
MenuItem item = menu.getMenu().add(f.key);
storedOption.put(count, f);
count++;
}
menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int position = info.position;
new ShowToast(context,Integer.toString(position)); // show position in a toast
return true;
}
});
menu.show();
}
}

You could use featureList.key as the key of your storeOption and them use item.getItemId(); to get the value from storeOption.
Like this:
public DynamicPopUpMenu{
private Map<String,FeatureList> storedOption = new HashMap();
public static void main(final Context context,List<FeatureList> featureList){
int count = 0;
PopupMenu menu = new PopupMenu(context, featureList);
for(FeatureList f:featureList) {
MenuItem item = menu.getMenu().add(f.key);
storedOption.put(f.key, f);
count++;
}
menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int id = item.getItemId();
FeatureList mFeatureList = (FeatureList)storedOption(id)
new ShowToast(context,Integer.toString(value)); // show position in a toast
return true;
}
});
menu.show();
}
}

Related

Global value becomes null in method

I have created a private member of the whole class called Member curMbr;
The activity (rather the fragment, since this is in a frament class) has a listview
with some contributions from members.
I also have a context menu on that list. When clicking on a contribution, I want a (customized) dialog box to show details about the member. (Member ID is part of the contribution objet. )
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
Log.d("FRGCOTIZ02", "create ctxt menu");
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
String[] menuItems = getResources().getStringArray(R.array.ar_menu_ctxt_participant);
// Get selected member
Contribution curCotis = (Contribution) (((ListView)v).getItemAtPosition(info.position));
Participant p = new Participant(helper.getDBItem(DBHelper.TABLE_PARTICIPANT,
DBHelper.COL_ID, curCotis.getParticipant()));
curMbr = new Member(helper.getDBItem(DBHelper.TABLE_MEMBER, DBHelper.COL_ID, p.getMember()));
for (int i = 0; i < menuItems.length; i++) {
menu.add(Menu.NONE, i, i, menuItems[i]);
}
Log.d("FRGCOTIZ01", curMbr.getId_());
}
#Override
public boolean onContextItemSelected(MenuItem item) {
return ( applyContextMenuSelection(item) || super.onContextItemSelected(item) );
}
private boolean applyContextMenuSelection(MenuItem item) {
switch (item.getItemId()) {
case 0: // Summary
final Dialog dlg = new Dialog(this.getContext());
final String sessID;
try {
sessID = KUtil.DATE_FORMAT.format(curSess.getDate());
dlg.setContentView(R.layout.alert_show_charges);
Button btnOK = dlg.findViewById(R.id.btn_alertOK);
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setupAlertDialogCharges(dlg, sessID, curMbr.getId_());
}
});
Button btnCancel = dlg.findViewById(R.id.btn_alertCancel);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dlg.dismiss();
}
});
dlg.show();
} catch (Exception e){
Log.d("FRAGMENT Contribution", e.getMessage());
}
break;
case 1: // Collect
break;
case 2: // Cancel
break;
default:
break;
}
return true;
}
In method onCreateContextMenu, I can get the member and display his ID.
But in method applyContextMenuSelection, there is an exception, saying the meber is null!
Funny enough there is another variable that I am using in that method, and it works fine. Difference is, that variable has been set at creation of the fragment.
How do I solve this?
I have been studying the code for a while and the only thing I could figure was that the issue is somehow linked to the use of contextmenu. It seems to me that variables are set back to their original when the menu action is supposed to be executed. Again, I am not too sure about that.
So, the only solution I found so far was to keep that vale in a "higher" context:
When I can still read the value,
getActivity().getIntent().putExtra(HomeActivity.ID_ENTRY, curMbr.getId_());
When I want to use it,
final String mbrID = getActivity().getIntent().getStringExtra(HomeActivity.ID_ENTRY);

Custom dropdown/popup with shorting ArrayList<Object>

i'll create a custom Dropdown/popup and it's work perfect.
See below Custom dropdown/popup code:
case R.id.linerSort:
PopupMenu popup = new PopupMenu(activity, linerSort);
//Inflating the Popup using xml file
popup.getMenuInflater()
.inflate(R.menu.popup, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(
activity,
"You Clicked : " + item.getTitle(),
Toast.LENGTH_SHORT
).show();
return true;
}
});
popup.show();
break;
Now i want to sorting a list which i select a item of Dropdown/popup.
Sorting is according to ArrayList<Object> So how to do that with my code.
if suppose i select a price then is shorting a acceding or descending order.
i follow this link: How to sort ArrayList<Object> in Ascending order android But how to i merge with my code i don't understand.
Try below code to sort in ascending or descending order:
case R.id.HighToLow:
Collections.sort(subCategoryViewDataBeanArrayList, new Comparator<SubCategoryViewDataBean>() {
#Override
public int compare(SubCategoryViewDataBean s1, SubCategoryViewDataBean s2) {
return Integer.parseInt(String.valueOf(s2.price)) - Integer.parseInt(String.valueOf(s1.price));
}
});
BindData(subCategoryViewDataBeanArrayList);
break;
case R.id.LowToHigh:
Collections.sort(subCategoryViewDataBeanArrayList, new Comparator<SubCategoryViewDataBean>() {
#Override
public int compare(SubCategoryViewDataBean s1, SubCategoryViewDataBean s2) {
return Integer.parseInt(String.valueOf(s1.price)) - Integer.parseInt(String.valueOf(s2.price));
}
});
BindData(subCategoryViewDataBeanArrayList);

I need to hide/show a particular item from popup menu on given condition

I tried this solution, but it doesn't work as I expected. Here is my code, and this is what i have tried.
PopupMenu popup = new PopupMenu(TableActivity.this, view);
popup.setOnMenuItemClickListener(TableActivity.this);
menu = popup.getMenu();
popup.inflate(R.menu.popup_shift);
popup.show();
popup.setOnMenuItemClickListener(this);
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_merge:
if(tableDbList.get(positionShift).getMergeTableId()== 0) {
//this is the condition to show/hide popup menuitem
popup.getMenu().findItem(R.id.menu_merge).setVisible(false);
}else {
checkPinCode.checkPinCodemethod(TableActivity.this, "mergeCancel");
}
}
return true;
}
You are trying to change visibility on MenuItem click . It will work but popupMenu will dismiss just after click . So it does not make any sense.
If your requirement is to show items on some condition you should set visibility before show(). Below is a simple example .
private void showPopup() {
final PopupMenu popup = new PopupMenu(MainActivity.this, view);
popup.getMenuInflater().inflate(R.menu.popup_shift, popup.getMenu());
if(someCondition){
popup.getMenu().findItem(R.id.menu_merge).setVisible(false);
}
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(MainActivity.this, "You Clicked : " + item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
});
popup.show();
}

Remove ListView items after 3 clicks

How to remove ListView items from ListView on Android?
But, I want to set a click on each item to 3 before removing it.
So if the item at the first position is clicked once and the second item clicked twice, do not remove any item until the first item click reaches 3. Then remove that item only and for other items in the ListView, each has to be clicked 3 times.
listi.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,final int position, long id) {
final PopupMenu pop = new PopupMenu(Danger.this, listi);
pop.getMenuInflater().inflate(R.menu.menu_location, pop.getMenu());
pop.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.Remove:
items.remove(position);
}//swithc
return false;
Create an ArrayList of integers and initialize it with exactly with same element count of your list view and set value of all elements of the list = 0
ArrayList<integers> counterList = new Arraylist();
for(int i = 0; i < listi.getAdapter.getChildrenCount(); i++){ // get total elements in adapter
counterList.add(0); // set each element of array list to 0
}
Then here:
listi.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,final int position, long id) {
final PopupMenu pop = new PopupMenu(Danger.this, listi);
pop.getMenuInflater().inflate(R.menu.menu_location, pop.getMenu());
pop.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.Remove:
if(counterList.get(position) >= 2){
items.remove(position); // remove current position item from arraylist adapter and notify data set changed
counterList.remove(position); // remove the current position element from counter list too
} else {
counterList.set(position, counterList.get(position) + 1); // if 3 clicks have not happened then increase the counter.
}
}//swithc
return false;
Use static variable and hold it with null,Include the static variable inside ClickListener , Once the variable reaches 3,you can remove the items from list view
I would suggest adding 2 fields: int timesClicked and int lastItemId, then in your onMenuItemClick method, check if the Item needs to be removed:
int timesClicked = 0;
int lastItemId;
...
#Override
public boolean onMenuItemClick(MenuItem item) {
if(item.getItemId() == lastItemId) {
if(timesClicked == 3) {
timesCliked == 0;
items.remove(item);
} else timesClicked++;
} else {
lastItemId = item.getItemId();
timesClicked = 0;
}
}
This should work.
Make a bean (Model) class for having record of clicked item according to
their corresponding position and every time on item clicked first check that
how many time this item is clicked if it's returning 2 then remove the item
else not.

Dialog when user hold a link

I have seen a lot of Android browsers which shows a dialog box when user holds a link or an image.
I am new to android and I have created a simple browser, and now I want to make this possible, so when user hold a link I have to show dialog like this
http://the.url.com
--------------------- Open Copy link address Select Text
Any tutorial or a sample code would be helpful.
You can use ContextMenu for that purpose.
//Constants for context menu options
public static final int MENU_OPEN= 1;
public static final int MENU_COPY= 2;
public static final int MENU_SELECT= 3;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
...
...
// Especify that your veiw have a context menu attached
registerForContextMenu(your view);
}
// here you create the conext menu
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
menu.add(Menu.NONE, MENU_OPEN, Menu.NONE, "Open");
menu.add(Menu.NONE, MENU_COPY, Menu.NONE, "Copy link address");
menu.add(Menu.NONE, MENU_SELECT, Menu.NONE, "Select Text");
}
// This is executed when the user select an option
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case MENU_OPEN:
return true;
case MENU_COPY:
return true;
case MENU_SELECT:
return true;
default:
return super.onContextItemSelected(item);
}
}

Categories