Android opening context menu after button click - android

I want to open context menu when I click a button, but also I have to know which list item is focused when I click the button. Do you know how to do that? What code should be in onclick method?

I was looking for the same, and found that instead of context menu, you should use Dialogs
final CharSequence[] items = {"Red", "Green", "Blue"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.show();
http://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog

If you really want to do it for whatever reason... (in my case, out of laziness)
During onCreate of your activity or somewhere before your user can touch the button, do registerForContextMenuon that button. Then in the actual button onClick handler, call openContextMenu(View).
For example, I have a button declared in xml like
<Button
android:id="#+id/btn_help"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onHelp"
android:text="#string/help_btn_text" />
in my onCreate
registerForContextMenu(findViewById(R.id.btn_help));
and in onHelp function
public void onHelp(View v) {
openContextMenu(v);
}
this works because the View v is the same as the view registered for context menu.

First thing, you should register the view by calling registerForContextMenu(View view). Second, override the onCreateContextMenu() to add the menus and lastly, override the onContextItemSelected() to put logic on each menu.

First of all, you should know why you should use ContextMenu. The functionality of ContextMenu of a View is similar to the right-click menu on a PC, which means the "available operations" on some item.
According to your description, I think what you actually need is a customized Dialog with a list, which is displayed when clicking the Button and is also able to get the focused item of your ListView. Then you can save the registration of ContextMenu for some View that really needs the menu:)

Related

How do I show a dialog fragment over another app when sharing from that app?

I'm making an app which other apps share/send to. When this happens, I want to show a dialog over the top of the existing app, the user chooses one of the options, then my app does something invisible and the user pops back to the original app - much like when you share something to Google+ but have multiple accounts set up, and it lets you choose which account to use.
Currently the activity (SendToActivity) which is started on the SEND intent is essentially a normal activity, made invisible with android:theme="#android:style/Theme.Translucent.NoTitleBar". Am I going down the right path by using a DialogFragment, and changing SendToActivity to extend FragmentActivity instead of AppCompatActivity?
I ended up using an AlertDialog, with an ArrayAdapter to make the list:
AlertDialog.Builder builder = new AlertDialog.Builder(SendToActivity.this);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
for(String[] player: players){
adapter.add(player[0]);
}
builder.setTitle("Which Player?");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
sendToPlayer(item);
}
});
AlertDialog dialog = builder.create();
dialog.show();

Android Listview dialog doesn't disapear after choosing an item

I've tried to create a list view dialog to display a list of choose. My code is shown below:
LayoutInflater factory=LayoutInflater.from(this);
final View stuckLevelDialogView=factory.inflate(R.layout.report_stuck_dialog, null);
final ListView stuckLevelListViewForDialog=(ListView)stuckLevelDialogView.findViewById(R.id.report_stuck_dialog_listview);
final String[] stuckLevelList=new String[]{"1 - You can move freely","2 - You have to be aware of your movement","3 - You can move slowly","4 - There is a traffic jam","5 - There is a serious traffic jam"};
ArrayAdapter<String> adapterForDialog=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, stuckLevelList);
stuckLevelListViewForDialog.setAdapter(adapterForDialog);
final AlertDialog.Builder stuckLevelDialog=new AlertDialog.Builder(this);
stuckLevelDialog.setTitle("What stuck level is this point?");
stuckLevelDialog.setView(stuckLevelDialogView);
stuckLevelDialog.show();
However, when I choose an option, the onItemClick is executed, but the listview dialog doesn't disappear, I have to press back button manually. I've tried to debug the code for a whole day, but it has not been solved yet. Please help me. Thank in advanced!
I think you need to dismiss() the dialog in your onItemClick listener as below:
stuckLevelListViewForDialog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> p_arg0, View p_arg1,
int p_arg2, long p_arg3) {
stuckLevelDialog.dismiss();
}
});
Use stuckLevelDialog.dismiss; at the end of onItemClick.
You can set setSingleChoiceItems in your alert dialog box with your items list, which will show a list with a radio buttons. If you want to add buttons you can else once user select any items you can dismiss the dialog.
new AlertDialog.Builder(this)
.setSingleChoiceItems(array, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// here you can do your functionality and can dismiss dialog as well
dialog.dismiss();
}
})
.show();

How to extend AlertDialog.Builder result?

I need to show an AlertDialog with a ListView and a context menu for the ListView items. I prefer to use AlertDialog.Builder and call setItems(), so the Builder creates a ListView inside the AlertDialog with stylized layout for me. For the stylizing it uses internal Android resources, so I cannot reimplement it in my code.
The problem is that I cannot catch a context menu item click event because of default AlertDialog.onMenuItemSelected() implementation, which does not forward such events to the parent:
public boolean onMenuItemSelected(int featureId, MenuItem item) {
return false;
}
I cannot extend AlertDialog.Builder class and force it to create an instance of my own AlertDialog with onMenuItemSelected() overridden because I need to override AlertDialog.Builder.create() for that. But it uses a private P variable, which is not accessible from a derived class:
public AlertDialog create() {
final AlertDialog dialog = new AlertDialog(P.mContext, mTheme, false);
P.apply(dialog.mAlert);
dialog.setCancelable(P.mCancelable);
if (P.mCancelable) {
dialog.setCanceledOnTouchOutside(true);
}
dialog.setOnCancelListener(P.mOnCancelListener);
if (P.mOnKeyListener != null) {
dialog.setOnKeyListener(P.mOnKeyListener);
}
return dialog;
}
Is there a way to force AlertDialog.Builder to construct a custom AlertDialog (with onMenuItemSelected method overridden)?
I still found no solution for the question, but I found some problems, which makes the solution useless. For Android 2.1, built-in ListView items (android.R.layout.select_dialog_item) are displayed as black text on dark grey background, ListView items are not separated from the dialog message (setMessage()), etc.
I finally switched back to my own AlertDialog with custom layout for ListView and its items (AlertDialog.Builer not used). Context menu events can be easily catched this way.
Luksprog, thanks a lot for your comments. But the main idea was to use as many stylized layouts, as possible. AFAIK, no standard layouts (android.R.layout.*) offer the buttons you mentioned. Also, an item could be removed occasionally with the button. With a context menu, at least two click required to remove an item.

Android: How to set the selection in a single choice AlertDialog?

I created a single choice AlertDialog with "Apply" and "Cancel" buttons. When the user presses "Cancel", I would like to set the selected item back to what it was when the dialog was first shown (I have the value stored already).
I know how to set the selected item when the dialog is first created in setSingleChoiceItems() but is there a way to set it again later?
I would like to be compatible with API level 7, so I'd rather not use onPrepareDialog().
Well, nobody could find a solution to my problem, so I settled for a dialog which doesn't use buttons. When the user presses an item in the list, that selection is applied and the dialog is dismissed. No need to remember previous choices or support cancelling.
You can create your dialog on the spot rather than going through showDialog and onCreateDialog. This way its always using the current selection we give to setSingleChoiceItems.
//where we display the dialog
showDialog(MYDIALOG);
AlertDialog.Builder builder = new Builder(this);
String[] choices = {"A","B","C"};
builder.setSingleChoiceItems(choices,current_choice,null);
builder.setPositiveButton("Select",null);
builder.setNegativeButton("Cancel",null);
builder.show();
...
protected Dialog onCreatDialog(int id) {
if (id==MYDIALOG) {
AlertDialog.Builder builder = new Builder(this);
String[] choices = {"A","B","C"};
builder.setSingleChoiceItems(choices,current_choice,null);
builder.setPositiveButton("Select",null);
builder.setNegativeButton("Cancel",null);
return builder.show();
}
return null;
}
In Altert Dialog For creating single choice have you used single choice list view or radio group?
If You have used Single Choice Listviwe then no need to worry.
IF you have used Radio Group then you have to keep track of selected Radio Button Using Global Varialbe in your activity.
What you want to do when user click on cancel.
when user click on cancel than do you want to remove selected item from list if yes then you have to do the following.
In Your listitemseleted listener
alb.setSingleChoiceItems(items, 0, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/* which argument is the position of the item in
array items you have to remove this item from items array
Make your items array global variable.since in java array are
immutable you have to use arraylist.Arraylist can be converted
to array.*/
}
});
hope this will help if any question feel free to ask.

In Android how do you get an alert dialog to add an item to a list if the user presses yes and viceversa

I am developing a simple Restaurant application in Android, I used menus and inflated submenu items corresponding to each menu item, I wanted to know a way of how to add the name of the dish to list only if the user selects yes in the alert dialog and viceversa.
Here is my code
public boolean onOptionsItemSelected(MenuItem m)
{
super.onOptionsItemSelected(m);
switch(m.getItemId())
{
case R.id.Chicken_Biryani:
selectedItem.add(m.getTitle().toString());
cost.add(150);
Toast.makeText(getApplicationContext(),"Hyderabadi special: Chicken biryani costs 150 Rs"+selectedItem, Toast.LENGTH_LONG).show();
showDialog(ALERT_DIALOG);
break;
case R.id.Butter_Chicken:
selectedItem.add(m.getTitle().toString());
cost.add(150);
Toast.makeText(getApplicationContext(),"Now with Punjabi Tadka: Butter Chicken costs 150 Rs", Toast.LENGTH_LONG).show();
showDialog(ALERT_DIALOG);
break;
........
public Dialog onCreateDialog(int id) {
switch(id)
{
case ALERT_DIALOG:
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setTitle("Buy Items");
ab.setMessage(" You have added the item to your cart ");
ab.setIcon(R.drawable.shopcart);
ab.setPositiveButton("Ok", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
Toast.makeText(getApplicationContext(),"Item added to cart your cart contains "+selectedItem.size()+" Items", Toast.LENGTH_LONG).show();
}});
Dialog ad = ab.create();
return ad;
}
return null;
}
// how do i pass the data of the onOptionsItemSelected to the list only if the user selects yes in the alertdiaolog
Please see this question for more information. It links to another answer which talks about how and when you can use notifyDataSetChanged.
I think in your AlertDialog you would want an "Add" button and a "Cancel" button to cancel adding it to the cart. Upon clicking add, your would insert the item into the users cart. To add another button to your AlertDialog you would use ab.setNegativeButton(...) just as you did with the setPositiveButton. This is just my take on it, am I correctly understanding your use of onCreateDialog - or is it used only to tell the user it has been added?
Please see this question for more specific help on how to implement within an AlertDialog.

Categories

Resources