I'm trying to make it so that a dialog pops up for users which has two buttons in the body and a cancel button at the bottom. When a user clicks one of the two buttons the dialog will disappear, and hitting cancel will just cancel out of the dialog. The cancel part works fine, but I can't figure out how to dismiss the dialog manually. Here's my code:
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
Context mContext = getApplicationContext();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.config_dialog,
(ViewGroup) findViewById(R.id.config_dialog));
Button connect = (Button) layout.findViewById(R.id.config_connect);
Button delete = (Button) layout.findViewById(R.id.config_delete);
alert = new AlertDialog.Builder(Configuration.this);
alert.setTitle("Profile");
connect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
trace("Connect" + Integer.toString(position));
toast("Connected");
SharedPreferences app_preferences =
PreferenceManager.getDefaultSharedPreferences(Configuration.this);
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("IP", fetch.get(position).IP);
editor.commit();
//Add dismiss here
}
});
delete.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
trace("Delete");
}
});
// Set layout
alert.setView(layout);
alert.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
When I try to add the alert.dismiss(), Eclipse gives me an error. .dismiss() also doesn't show up in alert's autocomplete list.
AlertDialog.Builder
is best suited for small simple dialog boxes rather than custom dialogs.The cleanest way to handle custom dialogs is to subclass
AlertDialog
as a private static class in your context (in this case your activity).Here is a simplified example:
The code is very simple:
finally in the action of button for example:
For example with a custom alertdialog:
Code on java, you could create a Object AlertDialog:
Code example XML: layout_test.xml
finally, call on Activity:
Merlin's answer is correct and should be accepted, but for the sake of completeness I will post an alternative.
The problem is that you are trying to dismiss an instance of AlertDialog.Builder instead of AlertDialog. This is why Eclipse will not auto-complete the method for you. Once you call create() on the AlertDialog.Builder, you can dismiss the AlertDialog that you receive as a result.
There's no need to create a custom class. Just create an external reference to your Dialog and use it to show/dismiss.
Here's an example where I use Builder to create a custom Dialog with many buttons:
Declare it within you class:
In your onCreate(), set when you want your Dialog to show up. In my case, I have a button:
And here's how it looks: