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.
Related
I'm developing an Android app. Currently I've implemented custom list view in Alert Dialog. This is the code so far:
private void setupAlertDialogBuilder(final Context context) {
GiftStoreCountriesAdapter giftStoreCountriesAdapter = new GiftStoreCountriesAdapter(context,
R.layout.gift_store_countries_row,
giftStoreCountriesViewModel.fetchCountriesFromLocalDatabase(),
(HomeActivity) context);
builder = new AlertDialog.Builder(context)
.setIcon(R.drawable.ic_currency_icon)
.setAdapter(giftStoreCountriesAdapter, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
handleCountrySelection(dialog, which);
}
});
builder.create().getListView().setFastScrollEnabled(true);
builder.create().getListView().smoothScrollToPosition(scrollToPosition(context));
}
Everything works fine except one thing. How can I programmatically scroll that custom list view to the some position or index of row as soon as alert dialog is shown to user. I've tried with this:
builder.create().getListView().setFastScrollEnabled(true);
builder.create().getListView().smoothScrollToPosition(scrollToPosition(context));
but it doesn't work. If I put just:
getListView().smoothScrollToPosition(scrollToPosition(context));
without builder.create() I get NullPointerException. This is in class that is custom Alert Dialog and it extends AlertDialog. I need to automatically scroll this list when it's shown to user. I appreciate all your help.
protected Dialog onCreateDialog(int id) {
switch (id) {
case Dialog_alert:
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
final LayoutInflater li = LayoutInflater.from(this);
builder.setTitle("Choose any option: ");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
setContentView(R.layout.tkentry);
// what to do after this..???
This is a dialog which asks the user to choose one of the following.
'items' is the String array which has "Update" and "Delete" options.
How to set separate onClick methods for them ?
"Update" and "Delete" are not BUTTONS!
You don't need two separate onClick method. You have to use int which to know which item is being selected.
If you want to know what item is selected you must add AdapterView.OnItemSelectedListener listener to your AlertDialog.Builder object.
builder.setOnItemSelectedListener (...);
You'll be notified when an item is selected so you'll be able to save it and when the confirm button is pressed you can take any action you want depending on the selected option.
I show dialog of checkboxes (list retrieved from DB) to allow user select, which rows remove. Because android dialog caching, I need to refresh count and names of checkboxes.
In my onCreateDialog:
dialog = new AlertDialog.Builder( this )
.setTitle( "Remove Items" )
.setMultiChoiceItems( items, _selections, new OnMultiChoiceClickListener(){public void onClick (DialogInterface dialog, int which, boolean isChecked){}} )
.setPositiveButton("Smazat", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
deleteRow(_selections);
} })
.setNegativeButton("Storno", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
} })
.create();
How refresh values (items,_selections) in onPrepareDialog?
I tried invalidate views, hoping that force android to load items againg(dont work neither), but I think its bad choice as well as removing dialog and recreating.
protected void onPrepareDialog(final int id, final Dialog dialog) {
switch (id) {
case REMOVE_DIALOG_ID:
ListView lv = ((AlertDialog) dialog).getListView();
lv.invalidateViews();
break;
}
Thanks for any ideas!
When you create a list of items using AlertDialog.Builder, it internally takes that and creates a ListAdapater that is dependent on the type of data you passed. Since "items" in your example doesn't look like a resource ID, I'm assuming it's either a CharSequence[] or a Cursor. If you provide more information about what "items" is, I can provide a more concrete example.
For CharSequence[] (like String[]) data, Builder creates an ArrayAdapter instance.
For Cursor data, Builder creates a CursorAdapter
You will need to obtain a reference to this ListAdapter using getListView().getAdapter() on the AlertDialog instance.
For a Cursor, you can get away with calling notifyDataSetChanged() after you have called requery() to update the data set.
Since you can't "update" an array with new data (changing the pointer to a new instance is not the same thing...the instance that the adapter is pointing to stays unchanged), this case is a little more work. You will need to call the add(), clear(), etc. methods of the adapter to remove invalid items and add the updates ones. With the adapters data set fully updated, you may now call notifyDataSetChanged().
Hope that Helps!
I spent lot of time to search for same solution and eventually fixed my problem with simple stuff after trying to use onPrepareDialog too
I use the removeDialog(int) function of the Activity. When a dialog is dismissed, the Activity basically stores the state of the dialog (for performance reasons I would imagine). Calling removeDialog(int) on the dialog forces the activity to unload all references for the dialog and dismisses it from the screen if it's being shown.
did this when my activity lost focus simply add:
public void onStop() {
removeDialog(Id_Dial);
return;
}
My technique is to create an adapter with empty data in onCreateDialog and completely replace the adapter during onPreparDialog.
Example:
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DialogMergeRegion:
title = ...
return new AlertDialog.Builder(BaseDataTabView.this)
.setTitle(title)
.setMultiChoiceItems(new CharSequence[0], null,
new OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
manageSelectionList(which, isChecked);
}
})
//...
.create();
}
}
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
switch (id) {
case DialogMergeRegion: {
List<String> regionNames = ...// get the data
ListAdapter mergeAdapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_multichoice, regionNames);
AlertDialog ad = (AlertDialog) dialog;
ad.getListView().setAdapter(mergeAdapter);
break;
}
}
In your onPrepareDialog method, instead of using invalidateViews(), you should try getting the adapter of the ListView and try calling either notifyDataSetChanged() or notifyDataSetInvalidated(). Does that help?
I'm using and ArrayAdapter to populate a ListView. After selecting and item, it displays a confirmation Y/N dialog. If the user's choice is negative, then he should be able to select another item showing the same dialog. And so on.
Here's my code:
lView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(final AdapterView<?> parent, final View v, final int index, final long id) {
Toast.makeText("Selected file"+ mFiles.get(index).getfileName(),
Toast.LENGTH_SHORT).show();
SelectedFile = mFiles.get(index);
showDialog(DIALOG_CONFIRMIMPORT_ID);
}
});
The weird thing is that while the "Toast" shows the clicked item every time, only the first selected item since the Activity is initiated is being passed to "SelectedFile". No matter how many times you click a diferent item, "SelectedFile" always assumes the same value, the value of the first clicked item, outside of this code.
Heres's my Dialog code:
Protected Dialog onCreateDialog(int id) {
switch(id) {
case DIALOG_CONFIRMIMPORT_ID:
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
String message = String.format(getString(R.string.importstudentfileconfirm),SelectedFile.getfileName());
builder.setMessage(message)
.setCancelable(false)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Activity.this.finish();
// startActivity(new Intent(Activity.this, LOL.class));
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
SelectedFile = null;
dismissDialog(DIALOG_CONFIRMIMPORT_ID);
mFiles.notifyAll();
}
});
AlertDialog alert = builder.create();
return alert;
}
}
return null;
}
Thank you very much for any help!
I'm guessing this has something to do with the fact that the onCreateDialog method is only called the first time the dialog is created. So the first time you see the dialog it will have the correct filename.
After onCreateDialog is called, onPrepareDialog(...) is called. onPrepareDialog, allows you to change the dialog after it has been created, but before it gets displayed.
Remember that underneath everything, Android isn't creating a new Dialog for you every time you want to show the DIALOG_CONFIRMIMPORT_ID dialog. It is too computationally expensive to instantiate a new dialog every time. Instead, it creates it once, which causes onCreatDialog to be called, followed by the onPrepareDialog. Every other time the dialog is shown, it only calls onPrepareDialog.
Check out the following article on the Android Developer site. It explains things pretty clearly.
http://developer.android.com/guide/topics/ui/dialogs.html#ShowingADialog
So try using onCreateDialog just for initialization of stuff that won't change between showings of the dialog, then use the onPrepareDialog method to dynamically update the contents of the dialog (i.e. getting the new filename)
Cheers!
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.