This question already has answers here:
How can I create positive and negative buttons at custom dialogs
(2 answers)
Closed 4 years ago.
I need to set positive and negative buttons for custom dialog.
public void newVisitorDialog(String title, String msg) {
Dialog visitorDialog = new Dialog(FindVisitorMobile.this);
visitorDialog.setCanceledOnTouchOutside(true);
visitorDialog.setContentView(R.layout.new_visitor_dialog);
TextView titleText = visitorDialog.findViewById(R.id.title);
titleText.setText(title);
TextView body = visitorDialog.findViewById(R.id.visitorData);
body.setText(msg);
visitorDialog.show();
}
Thanks,
Add Negative and Positive button in Xml layout.
Find the view of your button.
Set setOnClickListener for both negative and positive button.
Button negative = (Button) visitorDialog.findViewById(R.id.negative_btn);
Button positive = (Button) visitorDialog.findViewById(R.id.positive_btn);
negative.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//process your code here for negative
}
});
positive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//process your code here for positive
}
});
Do this:
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_fire_missiles)
.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES!
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
For custom dialogs you should include in your R.layout.new_dialog_visitor the two buttons.
Then in your newVisitorDialog method you find the buttons with the .findViewById and call the .setOnClickListener(..) on them.
If its a custom dialog you can create a whole another layout for it
Heres a link
It shows how to add buttons ,textview,images to a dialog.Hope it helps
I found the best way is to set the dialog as a private variable in the class.
private Dialog visitorDialog;
public void newVisitorDialog(String title, String msg) {
visitorDialog = new Dialog(FindVisitorMobile.this);
visitorDialog.setCanceledOnTouchOutside(true);
visitorDialog.setContentView(R.layout.new_visitor_dialog);
TextView titleText = visitorDialog.findViewById(R.id.title);
titleText.setText(title);
TextView body = visitorDialog.findViewById(R.id.visitorData);
body.setText(msg);
visitorDialog.show();
}
/**
* Cancel the visitor dialog
* #param view
*/
public void dialogCancel(View view){
visitorDialog.dismiss();
}
Related
I am using a dialog in my app that pops up and interacts with the user. I haven't worked with dialogs before, so i know next to nothing about styling them. This is the code:
public void openDialog() {
#SuppressLint("InflateParams") View view = (LayoutInflater.from(AudioRecorder.this)).inflate(R.layout.audio_name_input, null);
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(AudioRecorder.this);
alertBuilder.setView(view);
final EditText userInput = view.findViewById(R.id.userInput);
alertBuilder.setCancelable(true);
alertBuilder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
inputName = String.valueOf(userInput.getText());
if (!inputName.isEmpty()) {
Toast.makeText(AudioRecorder.this, "Next audio clip will be named... " + inputName, Toast.LENGTH_SHORT).show();
filePathMaking();
} else {
inputName = "recorded_audio";
Toast.makeText(AudioRecorder.this, "Input field empty, next audio clip will be named... " + inputName, Toast.LENGTH_SHORT).show();
}
}
});
alertBuilder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
Dialog dialog = alertBuilder.create();
dialog.show();
}
Can we style the "Save" button to display red text?
You can get the Button and then change it's text color. Something along the following lines should work,
public void openDialog() {
#SuppressLint("InflateParams") View view = (LayoutInflater.from(AudioRecorder.this)).inflate(R.layout.audio_name_input, null);
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(AudioRecorder.this);
alertBuilder.setView(view);
final EditText userInput = view.findViewById(R.id.userInput);
alertBuilder.setCancelable(true);
alertBuilder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
inputName = String.valueOf(userInput.getText());
if (!inputName.isEmpty()) {
Toast.makeText(AudioRecorder.this, "Next audio clip will be named... " + inputName, Toast.LENGTH_SHORT).show();
filePathMaking();
} else {
inputName = "recorded_audio";
Toast.makeText(AudioRecorder.this, "Input field empty, next audio clip will be named... " + inputName, Toast.LENGTH_SHORT).show();
}
}
});
alertBuilder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
Dialog dialog = alertBuilder.create();
dialog.show();
Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
positiveButton.setTextColor(Color.parseColor("#FF0B8B42"));
}
You can use AlertDialog as Chrisvin Jem suggested in his answer but I would like to offer another solution:
You can just create a custom dialog class in order to give your dialog a custom layout, control everything in a separate class - I find it cleaner and more organized.
For example, create dialogClass:
public class ProgressDialog extends Dialog {
public ProgressDialog(#NonNull Context context) {
super(context);
setContentView(R.layout.progress_dialog); //this is your layout for the dialog
}
}
And all you need to do is to create dialog instant and call it like this:
ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.show(); // this line shows your dialog
Why I recommend using this and not AlertDialog.Builder :
You can build your layout in a faster way with custom dialog.
No need to write a lot of code just to add views when you can have a custom layout.
It's easier (or so I believe) for you to see myCoolDialog.show(); rather than 50 lines of code or more in a single method.
Do you need to change anything regarding your dialog look and code? good, go to your separate class and change it instead of adding 20 more code lines to your activity.
Chrisvin Jem gave the extact answer to your question however if you want more control over your design you can the this code
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.yourview);
RelativeLayout submit = dialog.findViewById(R.id.submit);
final EditText edittext = dialog.findViewById(R.id.edittext);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
Toast.makeText(context, getString(R.string.thanks), Toast.LENGTH_SHORT).show();
}
});
dialog.show();
I want to create a function for dialog method and reuse the function later on.
Code to create a dialog within a function:
private void alertView( String message ) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle( "Hello" )
.setIcon(R.drawable.ic_launcher)
.setMessage(message)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i){
}
}).show();
}
Code to call this function:
alertView("My message");
This works fine but I want to center my message. I have looked for solutions and used various methods such as:
AlertDialog alert = dialog.show();
TextView messageText =(TextView)alert.findViewById(android.R.id.message);
messageText.setGravity(Gravity.CENTER);
messageText.setTextColor(Color.RED)
Nothing works. Could someone please help me with this?
Found a solution to my question from this website: http://examples.javacodegeeks.com/android/core/ui/dialog/android-custom-dialog-example/
Created an xml layout as described on the website and made a little change to the code in my java class:
private void alertView( String message ) {
//create a dialog component
final Dialog dialog = new Dialog(this);
//tell the dialog to use the dialog.xml as its layout description
dialog.setContentView(R.layout.dialog);
dialog.setTitle("your title");
TextView txt = (TextView) dialog.findViewById(R.id.txt);
txt.setText(message);
Button dialogButton = (Button)dialog.findViewById(R.id.dialogButton);
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mUartCom.write("D"); //change this
}
});
dialog.show();
}
and then I've reused this function numerous times by changing the message:
alertView("Please select one of the red icons to begin");
I am trying to include an AlertDialog builder within a method that prompts for a pin code and when the positive button is pressed, checks it against a database value and returns a true or false value to the method caller.
For example: Adding/editing/deleting a user task requires a pin code. I don't want to generate a different AlertDialog for all three (and more) of these actions. I want to wrap the following code within a TaskService class that I can call from any activity, and react based on the result from within that activity.
So TaskService.java would have:
public boolean isCorrectPin(View v){
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
final EditText editText = new EditText(context);
builder.setView(editText);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (editText.getText().toString()) == getPinCode(){
//return true
}
}
});
builder.show();
}
and OpenTaskAdapter.java would have:
public void onBindViewHolder(ViewHolder holder, int position){
holder.btnMarkAsComplete.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (service.isCorrectPin(v) {
//complete task
}
}
});
holder.btnDelete.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (service.isCorrectPin(v) {
//delete task
}
}
});
It's important to note that these two button listeners could be in totally different activities.
You can create your own method to generate dialog with listener:
public void isCorrectPin(Context context, String title, String message, String btnPositive, final DialogSingleButtonListener dialogSingleButtonListener) {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
dialogBuilder.setTitle(title);
dialogBuilder.setMessage(message);
dialogBuilder.setPositiveButton(btnPositive, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (editText.getText().toString() == getPinCode()){
dialogSingleButtonListener.onButtonClicked(dialog);
}
}
});
AlertDialog dialog = dialogBuilder.create();
dialog.show();
}
And the listener class:
public interface DialogSingleButtonListener {
public abstract void onButtonClicked(DialogInterface dialog);
}
And use it like:
service.isCorrectPin(context, title, message, btnPositive
new DialogSingleButtonListener() {
#Override
public void onButtonClicked(DialogInterface dialog) {
//code here is only called if they entered a correct pin.
}
}
);
A dialog can't "return" a value in the way that it looks like you're expecting. A dialog can make changes to some other object, but you can't have a bit of code block on it and wait for the user to finish interacting with it.
Instead, you'll need to set up listeners for when the prompt dialog is dismissed or buttons or clicked, or whatever other event signals that you have what you need from it. Those listeners can then read the data gathered and set by the dialog.
this is how i'm doing :
public Boolean showAlert(String message)
{
action = false;
AlertDialog.Builder alertDialog = new AlertDialog.Builder(HAActivity.this);
// Setting Dialog Title
alertDialog.setTitle(getString(R.string.app_name));
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting Icon to Dialog
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to invoke YES event
action = true;
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("Cancle", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
action = false;
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
return action;
}
and calling function like this :
//activity in which you create function
if (Activity.showAlert("Do you really want to delete ??"))
{
//delete it anyway.
}
I have the following code which displays a dialog box to the user if no network connection is detected.
private void createNoNetworkDialog() {
LayoutInflater inflater = LayoutInflater.from(this);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
View view = inflater.inflate(R.layout.offline_mode_dialog,null);
builder.setView(view);
builder.show();
}
There are two buttons in this dialog which have methods defined for their onClick actions. I would like to close the dialog pop-up after either of these button is pressed. Any ideas??
Yes,call dismiss() from the Listener's onClick since the DialogInterface reference is passed, which allows for dismissal.
Eg
builder.setPositiveButton ("Yes", new DialogInterface.OnClickListener()
{
public void onClick (DialogInterface dialog, int which)
{
//do stuff beforehand
dialog.dismiss();
}
});
Or if your buttons are inside the layout, show the dialog and keep a reference to it (final AlertDialog dialog = builder.show()). Then use dialog.findViewById() to find the respective buttons. Assign a normal View.OnClickListener and in it call dismiss() using the dialog reference you're holding.
Try this, Am using custom layout its working for me. inilitized Button custon_dialog.findViewById() and then write OncliclListner(). It will work
final Dialog custon_dialog = new Dialog(Login.this);
custon_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
custon_dialog.setContentView(R.layout.forget_custom_dialog);
custon_dialog.setCancelable(true);
Button submit_Btn = (Button) custon_dialog
.findViewById(R.id.submit);
Button cancel_Btn = (Button) custon_dialog
.findViewById(R.id.cancel);
submit_Btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//do your stuf
}
});
cancel_Btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
custon_dialog.dismiss();
}
});
custon_dialog.show();
}
I am developing an android application. Now i have created one function which create custom dialog box and i want this dialog box to display on every activity. So i need to call this function at every activity. But as the syntax of custom dialog (e.g. Dialog d = new Dialog(home.this)).home is the name of the activity where i have created the function so i am not ale to use this function in any other activity. And i haven't use android that much. So give me good example to solve my problem. Here is my code
here is sample code code of using AlertDialog in all activity.
crate one class file like as allmethod.java
and add this code in that class
public static void showAlert(Activity act,String msg)
{
AlertDialog.Builder alert = new AlertDialog.Builder(act);
alert.setMessage(msg).setPositiveButton("OK", new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which)
{
}
}).show();
}
and you can use from any class like as
allmethod.showAlert(Activity,"Message");
In your case..
public void SearchDialog(Context ctx){
final Dialog dialog = new Dialog(ctx);
dialog.setContentView(R.layout.dialogsearch);
dialog.setTitle(" Enter The Text to Search");
dialog.setCancelable(true);
final EditText Text = (EditText) dialog.findViewById(R.id.EdText);
Button buttonOK = (Button) dialog.findViewById(R.id.btnOK);
buttonOK.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String SearchText = Text.getText().toString();
prefsPrivate =getSharedPreferences(Login.PREFS_PRIVATE,Context.MODE_PRIVATE);
Editor prefsPrivateEdit=prefsPrivate.edit();
prefsPrivateEdit.putString("Text",SearchText);
prefsPrivateEdit.commit();
Intent i = new Intent(ctx,SearchTask.class);
startActivity(i);
dialog.cancel();
}
});
Button buttonCancel = (Button) dialog.findViewById(R.id.btnCancel);
buttonCancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.cancel();
}
});
dialog.show();
}
Just add a Context parameter to your SearchDialog() constructor.
Make it like this:
public SearchDialog(Context context){
//....
}
You could either define your own Interface and implement for every class, or make the main Activity method static (as long as it wont need to access anything in dynamic objects that aren't method arguments).
final class Uutil {
public void static func() {
}
}
then do it in your classes:
class A {
public void f() {
Uutil.func();
}
}