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();
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();
Please, i would like to show back details after the user must have input something, back on alert dialog box in Android studio. I used this code below:
editText = (EditText) findViewById(R.id.my_edit_txt);
editText.getText().toString();
But it doesn't show on the confirmation dialog box I created.
It looks like you didn't set the text of your AlertDialog, but this is just an assumption because there is not enough code in your question. Calling editText.getText().toString() does not do anything but return a String. It does not assign it to anything. An example with an AlertDialog would be the following:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(editText.getText().toString());
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Set other dialog properties
...
// Create the AlertDialog
AlertDialog dialog = builder.create();
I've took this example from Android Developers and modified it so that it includes the text of your EditText. This code should work because you not only call the toString() method but also assign it's return value to the AlertDialog's message property.
This is my entire code for the alert dialog box:
public void alertdialog(View view){
mybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder cfmalt = new AlertDialog.Builder(Dashboard.this);
//cfmalt.setMessage("Do you want to quit?").setCancelable(false);
//editText.getText().toString();
cfmalt.setMessage(editText.getText().toString()+"\n"+ vol_edit2.getText().toString());
cfmalt.setMessage(dt.getMonth())
//cfmalt.setMessage("Name:").setMessage(vol_edit2.getText().toString());
cfmalt.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
cfmalt.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
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'm a beginner for Java as well as for Android Studio so, here my problem is: I had created a alert dialog window for an activity with positive button being "OK" and negative button being "No thanks". As shown in the code below.
if(Times==0) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setIcon(android.R.drawable.ic_dialog_alert);
builder1.setTitle("Warning");
builder1.setMessage("Rooting of a phone may void your Warranty in most of the cases,so it is adviced to proceed at your own risk");
builder1.setCancelable(true);
builder1.setPositiveButton(
"OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Times += 1;
dialog.cancel();
}
});
builder1.setNegativeButton(
"No Thanks",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
}
It was going fine but now the catch is I want it to be displayed only once if the user clicks the "OK" button and don't want to show it again if the user clicked "OK". I had created a variable times in my class and initialised it to zero as shown below.
public class rootingRooting extends AppCompatActivity {
int Times=0;
and put the complete AlertDialog in the if loop and incremented it's value when the user clicked "OK" so that the loop may execute only once if the user clicked "OK", but it is of no use whenever I open the activity the alert box is being displayed inspite of clicking "OK". So, now the things i want to do happen is:
The alert box should not be displayed if the user once clicked "OK".
If the user clicked the "no Thanks" button, I want to take him to the home activity. So, how should I use the intent with the "no thanks" button?
Thank you.
You need to use SharedPreferenes to save data persistently, local variables will not help.
something like this:
EDIT As per your request, I have added a sample activity class to show the whole process. See the comments in between for more info
EDIT 2 See the code after //Second Edit comment
public class MainActivity extends AppCompatActivity {
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//When the activity starts, we look into the shared prefs and get an int of name "ok_clicked" from it.
//0 will be the default value of the int if there is no int stored in sharedPreferences.
prefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
int times = prefs.getInt("ok_clicked", 0);
//if the times value is 0, we will open the dialog, otherwise nothing happens
if (times==0){
openDialog();
}
}
//Read This comment First: We will create a Method, which create an alert Dialog.
private void openDialog(){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Test").setMessage("Lorem ipsum dolor");
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//When OK button is clicked, an int with value of 1 will be saved in sharedPreferences.
prefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("ok_clicked", 1);
editor.apply();
}
});
dialog.setNegativeButton("No Thanks", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Second Edit: To open another acitivty on No Thanks Button
Intent intent = new Intent(MyActivity.this, HomeActivity.class);
startActivity(intent);
}
});
dialog.show();
}
}
I'm trying to do alert message by disable ok and cancel button if the checkbox is unchecked.
reconfirm.java:
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(reconfirm.this);
LayoutInflater layoutInflater
= (LayoutInflater)getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
alertDialogBuilder.setView(popupView);
CheckBox check= (CheckBox)findViewById(R.id.checkBox1);
if (check.isChecked() ) {
AlertDialog dialog = null;
((AlertDialog)dialog).getButton(DialogInterface.BUTTON_POSITIVE).setVisibility(View.INVISIBLE);
}
alertDialogBuilder.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intObj = new Intent(getApplicationContext(),
agree.class);
startActivity(intObj);
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intObj = new Intent(getApplicationContext(),
IntentExampleActivity.class);
startActivity(intObj);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
This is answered already here--How to disable / enable dialog negative positive buttons?
after dialog.show use below code
if(your_condition_true)
dialog.getButton(AlertDialog.BUTTON1).setEnabled(false); //BUTTON1 is positive button
Try Using setEnabled() and setClickable method for buttons.
here is the doc
Try following code snippets. Hope you get some idea from this :)
if (check.isChecked()) {
alertDialogBuilder.getButton(Dialog.BUTTON_POSITIVE).setEnabled(false);
alertDialogBuilder.getButton(Dialog.BUTTON_NEGATIVE).setEnabled(false);
}
where dialog is object of AlertDialog.