How to align message in dialog function and reuse the function? - java

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");

Related

Visual customization of a dialog button

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();

How set buttons in custom android dialog? [duplicate]

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();
}

Is it impossible to put another popup in a popup message via builder in android?

I almost finished building an app using android studio. However, I noticed some problems in the testing process.
Here is a brief summary of what I'm doing:
When you click 'button', a popup message appears.
The popup message has two buttons.
Pressing the first button only ends the popup message.
When you press the second button, the current popup message is terminated and additional popup messages appear.
The second popup message has a button and an 'EditText' area for entering the email address.
When you click the button, the popup message ends with performing the Javascript function using the email address entered in the EditText area.
First of all, clicking on the two buttons and entering an email address works normally. But when I do this again for the second time, the app is terminating unexpectedly. I think the 'Builder' part I used to implement the popup message is incorrectly nested, but I can not figure out which part is the problem.
Each pop-up message is implemented using 'Builder' as shown below.
final AlertDialog.Builder builder; //for first popup message
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(context, android.R.style.Theme_Material_Dialog_Alert);}
else {
builder = new AlertDialog.Builder(context);}
final AlertDialog.Builder builder2; //for second popup message
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder2 = new AlertDialog.Builder(context, android.R.style.Theme_Material_Dialog_Alert);}
else {
builder2 = new AlertDialog.Builder(context);}
Now the full popup message implementation code. Sorry for the difficulty of reading the code.
button_makingpopup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (User.getInstance() != null) {
builder.setCancelable(false) //first popup setting
.setMessage("Do you want to email the measurement data??")
.setPositiveButton("Save and Send", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel(); //first popup disappear
builder2.setCancelable(false) //second popup setting
.setMessage("Enter your email address below.")
.setPositiveButton("Send", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String email_popup = input.getText().toString();
WebView view2 = new WebView(context);
view2.getSettings().setJavaScriptEnabled(true);
view2.getSettings().setDomStorageEnabled(true);
view2.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:(function() { //some javascript function})()");
}
});
dialog.cancel(); //second popup disappear
}
});
AlertDialog alert_send = builder2.create();
alert_send.show(); //second popup appear
}
})
.setNegativeButton("Save only", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel(); //first popup disappear
}
});
AlertDialog alert = builder.create();
alert.show(); //first popup appear
}
else
//Non-question parts
I would appreciate your advice.
environment: android studio 2.3.3
error message "java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first."
I solved this problem by handling the view.
I refer to this. #kasgoku
Thank you also for those who gave me advice by the comment.

How to getText() from a TextView in an AlertDialog?

I have an AlertDialog that opens pressing a Button.
In this AlertDialog there are a button and a TextView showing a number.
I have to create a function that increments by 1 the number in the TextView when the button in the AlertDialog is pressed.
In order to do that, I wrote this into the .java file of the activity that opens the AlertDialog.
public void plus(View view)
{
TextView total = (TextView) findViewById(R.id.Total);
totalP = Integer.parseInt((String)(total.getText())) + 1;
total.setText(String.valueOf(totalP));
}
But it gives error on total.getText()
I tried to write something similar, but with the TextView into the activity, and it works fine.
I started programming Android a week ago, I'm not very good. Please, help me!
Thank you!
If your dialog variable is named diag, then try the following
TextView total = (TextView) diag.findViewById(R.id.Total);
Notice that you are calling the findViewById() on the Dialog not the Activity
final EditText input = new EditText(MainActivity.this);
input.setSingleLine(true);
new AlertDialog.Builder(MainActivity.this)
.setTitle("Title")
.setView(input)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String in = input.getText().toString();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.show();

Closing an AlertDialog box after a button has been clicked

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();
}

Categories

Resources