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.
Related
I have implemented the Alert dialogue with checkbox and item name, I am not using any custom adapter to show the list view.I am able to display the items with checked states successfully but my problem is when ever i scroll the alertbox some of checkbox are unchecked.Could please suggest me how can i resolve this issue.
Please find the code for showing alert box with MultiChoiceItems.
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setPositiveButton(android.R.string.ok, this)
.setOnCancelListener(this)
.setTitle("title")
.setMultiChoiceItems(nameofItems, Checkedstates, listner);
mDialog = builder.create();
mDialog.show();
When you scroll list it update the view using data list so if you want your back check status, you have to update data list as well. Update your data list by using DialogInterface OnMultiChoiceClickListener.
OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
Checkedstates[which] = isChecked;
}
}
I have a little problem with a Dialog.
It's a ListView of Videos with thumbnails that load the videos with an Adapter. The ListView register an OnItemClickListener and inside the OnClickItem method I try to raise the Dialog.
I've tried with various types of Dialog but nothing happened. A simplified piece of code it's here:
public class ListOfVideos extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_of_videos);
init_phone_video_grid();
}
private void init_phone_video_grid() {
// Here's some code for the video reading
// The ListView
videolist = (ListView) findViewById(R.id.PhoneVideoList);
videolist.setAdapter(new VideoAdapter(getApplicationContext()));
videolist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Here's some code for the video reading
/** ============= Here's the problem ================ **/
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
builder.setMessage("Example Message")
.setTitle("This is the title!!")
.setCancelable(false)
.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
System.out.println("[debug]" + "Open File " + filename);
}
});
}
The list of videos load perfectly. But when I click on an Item:
The Dialog does not show
I got a error message in the LogCat, that state: "show() Dialog's window is null!"
The println debug message, appears ok in the LogCat
I have searched for that message error, but there's not much information.
I think the problem could be on the Context that receive the Builder, but I'm stuck on this point.
Any advice will be apreciated
That error message is saying that the Context given to the AlertDialog.Builder has no attached window, which Dialogs need as a UI anchor, basically. An Activity is what should be used for such a Context, as it will have the required window.
Without seeing VideoAdapter's code, the root cause is presumably new VideoAdapter(getApplicationContext()), which is handing your VideoAdapter the application Context to build Views with. That likely means that the v passed into onItemClick() is one such View, and v.getContext() is returning that application Context in new AlertDialog.Builder(v.getContext()).
That application Context does not have a window but your Activity does, as mentioned. Furthermore, the Activity is actually what you want to give to VideoAdapter to build Views with anyway, to ensure that they are created with the correct theme and styling. Change that relevant line to:
videolist.setAdapter(new VideoAdapter(ListOfVideos.this));
That alone might solve the issue, depending on what VideoAdapter does internally. However, it's arguably better to specify the Activity again in the AlertDialog.Builder constructor call, just so there's no question:
AlertDialog.Builder builder = new AlertDialog.Builder(ListOfVideos.this);
As a final note, whenever a Context is needed for any UI component, you usually want to use the immediately available Activity.
Here is a example of How to create dialog box..
String message = "Hello";
AlertDialog.Builder alt_bld = new AlertDialog.Builder(
CurrentActi.this);
alt_bld.setTitle("Alert")
.setMessage(message)
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//here right the code that you want perform onClick
dialog.cancel();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
alert.setTitle("Alert");
alert.show();
May be it will help you..
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();
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'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!