I have a custom alert dialog. I am currently trying to alter the onclicklisteners for my two buttons. Previously I have used the following code.
builder.setNegativeButton("Nope", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
});
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
\\code here which is not relevant to question
}
});
However, now since the dialog has a custom view and custom buttons, I use the following approach.
Button confirm = (Button) windowView.findViewById(R.id.confirmbutton);
Button cancel = (Button) windowView.findViewById(R.id.negatebutton);
cancel.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v){
}
});
My question is how do I dismiss the dialog within the cancel button listener if I can't access the dialog variable. I want to use the AlertDialog I am already using and do not want a solution with a different type of dialog.
What you need to do, is just keep a reference of the Dialog, then you can call the dismiss method. In my example, i keep the reference as a property.
private Dialog dialog;
#Override
public void onResume() {
AlertDialog.Builder adb = new AlertDialog.Builder(this);
LinearLayout llView = new LinearLayout(this);
Button btnDismiss = new Button(this);
btnDismiss.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
llView.addView(btnDismiss);
adb.setView(llView);
dialog = adb.create();
dialog.show();
super.onResume();
}
It's important keep the reference as a property, cause the reference must be final to be accessible inside the onClick method, and since the dialog it's not created yet, you cant keep the final reference in a method variable, then keep it in a property.
Related
This question already has answers here:
How can I change default dialog button text color in android 5
(18 answers)
Closed 4 years ago.
i am working in a social app and while the user wants to edit their feeds i want to give them a pop up alert dialog from where the user can edit their post. I tried the following code but the result that gave was not good
i want to change the color and want a better design .. what can be done for this
private void EditCurrentPost(String description)
{
AlertDialog.Builder builder = new AlertDialog.Builder(ClickPostActivity.this);
builder.setTitle("Edit post");
final EditText inputField = new EditText(ClickPostActivity.this);
inputField.setText(description);
builder.setView(inputField);
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ClickPostRef.child("description").setValue(inputField.getText().toString());
Toast.makeText(ClickPostActivity.this,"Post Updated",Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
Dialog dialog = builder.create();
dialog.show();
dialog.getWindow().setBackgroundDrawableResource(android.R.color.holo_purple);
}
There is a very simple way to make dialog with custom layout: Please review the code below:
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dialog_news_description);//Your custom layout
TextView sometextview = dialog.findViewById(R.id.textView);// Textview in your custom layout
Button somebutton = dialog.findViewById(R.id.button_done);// Button in your layout
somebutton.setOnClickListener(new View.OnClickListener() {//on button click listener
#Override
public void onClick(View view) {
//DO your job....
//then...
dialog.dismiss();//dismiss the dialog
}
});
dialog.show();
You cannot change the default AlertDialog layout but you can inflate a custom layout to it. To start with you can check this post http://android-coding.blogspot.com/2011/07/create-custom-dialog-using.html
Initially in my app I am creating an AlertDialog which has three buttons, in which the middle button opens up another AlertDialog. The problem is that when the second AlertDialog closes after a button is pressed, the first one closes with it. I think both AlertDialogs get closed after I press a button on the second AlertDialog.
What I want is for the first AlertDialog to open another AlertDialog that has its own buttons, and when second AlertDialog presses a button, it only closes itself and goes back to the first one. Is there any way to achieve this?
Here is the code for the button used to open the AlertDialog:
final ImageButton fabgroup = (ImageButton) findViewById(R.id.groupButton);
Here's the code for a button that opens an AlertDialog that contains another button that opens another AlertDialog using the middle button (create button) on itself, but closes them both when a button on the second one is pressed (either the yes or no button, which is not what I want as I only want the second one to close itself and go back to the first AlertDialog, and yea this sounds pretty confusing in theory so I can try to clarify if needed):
fabgroup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final AlertDialog.Builder helpBuilder = new AlertDialog.Builder(CreateNote.this);
helpBuilder.setTitle("Select a group");
helpBuilder.setMessage("Add to group?");
final TextView input = new TextView(mainactiv.this);
input.setSingleLine();
input.setText("");
helpBuilder.setView(input);
helpBuilder.setNegativeButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do nothing but close the dialog
Toast.makeText(CreateNote.this, "Page has been added to group", Toast.LENGTH_SHORT).show();
}
});
helpBuilder.setNeutralButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//open another alertbox
AlertDialog.Builder helpBuilder2 = new AlertDialog.Builder(CreateNote.this);
helpBuilder2.setTitle("Assign a new group");
helpBuilder2.setMessage("Create group?");
final EditText input = new EditText(CreateNote.this);
input.setSingleLine();
input.setText("");
helpBuilder2.setView(input);
helpBuilder2.setNegativeButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Create Group
Toast.makeText(CreateNote.this, "Group has been created", Toast.LENGTH_SHORT).show();
}
});
helpBuilder2.setPositiveButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
}
});
// Remember, create doesn't show the dialog
AlertDialog helpDialog2 = helpBuilder2.create();
helpDialog2.show();
}
});
helpBuilder.setPositiveButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
}
});
// Remember, create doesn't show the dialog
AlertDialog helpDialog = helpBuilder.create();
helpDialog.show();
}
});
Help would be greatly appreciated.
I eventually managed to solve this problem by creating two separate functions to generate each dialog box, and when one closes it calls the function to create the other one, kinda like recycling (or maybe closer to looping functions). Although, I'm not entirely sure how performance heavy this is, but it seems to do the job without any issues from what I'm testing. If anyone would like to chime in on how this could be an issue, then I'm open to hearing what others have to say about the negative points of using alert dialog boxes this way.
You can show an activity as dialog. Put this in your manifest file.
<activity android:theme="#android:style/Theme.Dialog" android:excludeFromRecents="true"/>
From this answer: Android Activity as a dialog
How can I achieve to show a Dialog automatically when an activity starts.
If the activity is started a Dialog must be shown, where you must type a password.
This password will be checked with the password stored in sharedpreferences, and if it is
correct this activity will be shown,if not, a message will be shown on the dialog that the password is wrong and he must type it again.. I looked for some tutorials but all of them used a button to start the AlertDialog, but in my case It mus be shown when a specific activity is called.
How can I achieve it?
Add this in your manifest, in the activity you want to look like dialog, declaration:
<activity android:theme="#android:style/Theme.Dialog">
for more information and themes: http://developer.android.com/guide/topics/ui/themes.html
furthermore, to this proggramatically you can use the following code:
public class ShowDialogActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//
//Log.d("DEBUG", "showing dialog!");
Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.select_dialog_singlechoice);
dialog.setTitle("Your Widget Name");
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
TextView text = (TextView) dialog.findViewById(R.id.text1);
text.setText("Message");
dialog.show();
//
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
finish();
}
});
}
}
You can choose whatever layout you wish for the dialog and design it as you want.
In addition you would need to set this activity declaration in the manifest for the following:
<activity android:name=".ShowDialogActivity"
android:theme="#android:style/Theme.Translucent.NoTitleBar">
</activity>
Hope this is what you was looking for.
in your oncreate method add this alert dialog code,and validate the input from edittext
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.layoutname);
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Title");
alert.setMessage("Message");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText();
// Do something with value!
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
Another solution is:
do not show dialog,create an activity which looks like dialog,create activity and give it a dialog look:
<activity
android:label="#string/app_name"
android:name=".DialogActivityDemoActivity"
android:theme="#android:style/Theme.Dialog" >
</activity>
now make this activity a launcher activity,validate user's input then start your main activity.
I want to display an alert dialog in my app. I am using fragments. I tried the below code to do this:
AlertDialog ad = new AlertDialog.Builder(context)
.create();
ad.setCancelable(false);
ad.setTitle(title);
ad.setMessage(message);
ad.setButton(context.getString(R.string.ok_text), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ad.show();
but it was crashing and the error in logcat was:
04-18 15:23:01.770: E/AndroidRuntime(9424): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
From internet I came to know that the crash is due to context issue. I had given context as
context = this.getActivity().getApplicationContext();
I don't know what is the problem with this. Can anybody help me?
Replace context with getActivity().
The ApplicationContext should not be used for tasks such as creating Dialogs. As you are in a fragment you can instead get the Activity-Context simply by calling the Fragments getActivity() method.
More Information about this question (AlertDialog in a fragment, managed inside an event):
If you call AlertDialog within an event like onClick(View v) or onLongClick(View v) you can use
public boolean onClick(View v) {
...
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(v.getContext());
...
}
Try to use DialogFragment, DialogFragment is better when you use Fragments
I have had similar issues whereby I was trying to create an AlertDialog from a Fragment. A NullPointerException arose from it. Initially I did as follows:
AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
The NullPointerException occurred specifically when calling alertDialog.show() later on in the code.
But after searching the documentation for AlertDialog.Builder(), there seemed to be another way to initialize it [AlertDialog.Builder Doc], which is to include a theme/resId as shown below:
AlertDialog alertDialog = new AlertDialog.Builder(getActivity(), R.style.Theme_AppCompat_Dialog_Alert).create();
This resolved the NullPointerException at hand. Hope this helps you as well!
I used it in an adapter inside a listView, therefore I couldn't use getActivity(). In order to make it work I used getActivity() for the context in the instantiation of the adapter in the fragment:
this.adapter = new myAdapter(getActivity(), factory);
Later in the other class (the adapter's class) I was able to use getContext()and it worked.
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
AlertDialog alert= null;
AlertDialog.Builder build= new AlertDialog.Builder(getActivity());
build.setTitle("title");
build.setItems(stringarrayname, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//Toast.makeText(getActivity(), "hi", Toast.LENGTH_SHORT).show();
}
});
build.create().show();
You can try this or use DialogFragment
private void showAlert(final int position) {
new AlertDialog.Builder(getActivity().getApplicationContext())
.setTitle("Delete entry")
.setMessage("Are you sure you want to delete this entry?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// deleteSuggestions(position);
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
The solution is to replace by getActivity()
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity(),R.style.MaDialog);
I've got an onCreateDialog method in my activity, which has a case switch to bring up different dialogs that I want to display depending on the request.
I cannot use the showDialog() method from my view because it's not accessible from the context that is passed when the view is created. At least, I can't find a way to access it.
How do I use showDialog from my application's view? Do I need to create a listener? And if so, how? Is there a better method?
Here is my onCreateDialog code that exists in my application's activity:
protected Dialog onCreateDialog(int id) {
AlertDialog alert=null;
switch(id) {
case DIALOG_GAMEOVER_ID:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("You died. Play again?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//init();
//oGameState = eGameState.PLAYING;
dialog.cancel();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
alert = builder.create();
break;
default:
break;
}
return alert;
}
I tried passing a reference to my activity, and I get crashes. Perhaps I am doing it wrong?
In my activity:
// set our MainView as the View
oNebulaMainView = new NebulaMainView(this, this);
setContentView(oNebulaMainView);
In my view:
public NebulaMainView(Context context, Activity oActivity) {
super(context);
// adding the callback (this) to the surface holder to intercept events
getHolder().addCallback(this);
// create the game loop thread
thread = new NebulaMainThread(getHolder(), this);
setFocusable(true);
oActivity.showDialog(DIALOG_GAMEOVER_ID);
}
I may be missing something here, but what is stopping you from just calling:
alert.show()
Just make the alert accessible to the view, and call that form inside your view.
declare alert as an instance variable