Is there any difference between these methods? I'd like to create the dialog first so that I have the reference to it when something is clicked in the view to dismiss it. Obviously that's not possible if I'm setting the view with the builder and the alert is not created yet.
As per AlertDialog.Builder source it makes no difference.
"I'd like to create the dialog first so that I have the reference to
it when something is clicked in the view to dismiss it."
The user can't click to dismiss the dialog until to you show it to them, and that is after you have created an instance. See the lifecycle example below:
View someView = ...;
View someOtherView= ...;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//sets the view, but doesn't show anything.
builder.setView(someView);
//now we have an instance of AlertDialog, still not shown
AlertDialog dialog = builder.create();
//now we showed it
dialog.show();
//...(wait some time)
//now we changed its view after being shown
dialog.setView(someOtherView);
Related
Am posting this in hopes to help someone else; but, if there is an easier way to do the same, I hope someone can share their steps. If I use the method 'setDisplayedValues' to pass an array of values to display in the NumberPicker, the underlying method forces the use of a Text Keyboard Layout, instead of the Number Layout, which isn't what I want.
I found a way to set the InputType for my NumberPicker. This is done in my extended class:
class public class NumberPickerDialogFragment extends DialogFragment:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// We are getting the parameters passed in to figure out the range of the Number Picker
NumPickerValues = getArguments().getStringArray("NumPickerRange");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
View dlgNumPicker = inflater.inflate(R.layout.dialog_num_picker, null);
NumberPicker np = (NumberPicker) dlgNumPicker.findViewById(R.id.npNumberPicker);
// Always remember that NumberPicker methods need an index position, rather than the value in that array position
np.setMinValue(0);
np.setMaxValue(NumPickerValues.length-1);
np.setDisplayedValues(NumPickerValues);
np.setValue(getArguments().getInt("InitialValue"));
np.setWrapSelectorWheel(false);
np.setOnValueChangedListener(this);
// Since the underlying code for the NumberPicker sets the keyboard layout for text, due to the use of 'setDisplayedValues',
// we need to set it back to a number keyboard layout
((EditText)np.getChildAt(0)).setRawInputType(InputType.TYPE_CLASS_NUMBER);
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
return builder.setView(dlgNumPicker)
.setTitle(getArguments().getInt("NumPickerTitle"))
.setPositiveButton(getArguments().getInt("SaveButtonTitle"), new ButtonCLickListener())
.setNegativeButton(R.string.cancel, new ButtonCLickListener())
.create();
}
On the section of code above, the line that sets the InputType is
((EditText)np.getChildAt(0)).setRawInputType(InputType.TYPE_CLASS_NUMBER);
I didn't find anything on the web that does this. It seems like a clean way of doing it; but, am not sure if there is any performance issues by doing it this way. If there is, let us know.
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.
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:)
Could someone point out a working example of a custom dialog that takes an ArrayAdapter as input and shows a selectable list.
I have tried to create a Dialog using an AlertDialog Builder as such...
final ArrayAdapter<MyObject> myAdapter = getMyobjects();
final AlertDialog.Builder builder = new AlertDialog.Builder(this).setTitle("Pick an item").setAdapter(myAdapter,
new android.content.DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int item) {
Toast.makeText(Islands.this, myAdapter.getItem(item).toString(), Toast.LENGTH_SHORT).show();
}
});
final AlertDialog alert = builder.create();
return alert;
My problem is that my dialog is not updating then i called
#Override
protected void onPrepareDialog(final int id, final Dialog dialog) {
switch (id) {
case DIALOG_GET_AVAIL_DESTS:
((AlertDialog) dialog).getListView().setAdapter( getDestinations());
break;
}
}
However the onClick listener listens to the initial set of items...
Indeed AlertDialog is implements Facade design pattern with this class behind :
http://www.netmite.com/android/mydroid/frameworks/base/core/java/com/android/internal/app/AlertController.java
And the whole code is such a mess...
I took 3 hours to try to do that, and I am going to build a dialog from scratch, using android.R.layout as a basis.
Steff
You have to make a call to
invalidateViews()
on your listview - that will cause it to redraw the view with the updates.
Since you are using onPrepareDialog(int id, Dialog dialog), I am guessing you're initially setting up the dialog in onCreateDialog(int id).
Doing so cause the system to save the dialog you initially create. In order to achieve the desired functionality, when the dialog is dismissed, tell the system to discard it by calling android.app.Activity.removeDialog(int id).
Any subsequent invocations will have your dialog regenerated through the onCreateDialog(int id) method, causing the set of items to be updated.
I want to know the process or order of creating the AlertDialog. The order of I asking this question is that I suppose to filter and disable some list item in the AlertDialog. It this must be dynamically. So I chose overwrite the onPrepareDialog(int id, Dialog dialog) method.
First I create a AlertDialog in the onCreateDialog(int id) method
protected Dialog onCreateDialog(int id) {
--------
builder.setMultiChoiceItems(itemsId, checkedItems, mListenter);
---------
}
protected void onPrepareDialog(int id, Dialog dialog) {
-----------
ListView mListView = ((AlertDialog)dialog).getListView();
mListView.setItemChecked(0, false);
mListView.invalidateViews();
View view = mListView.getChildAt(0);
-----------
}
But these code not work. The first item was still be checked after I check it before.
And the ChildView is null when the first time display the dialog, why?
How to filer some item in ListView and how to disable but show some of items.
Check and see if my answer over at: How to update array of items in an AlertDialog list built with AlertDialog.builder after creation fits the bill. It works for me, at least.