How do you disable a button inside of an AlertDialog? - java

I am trying to write an AlertDialog with 3 buttons. I want the middle, Neutral Button to be disabled if a certain condition is not met.
Code
int playerint = settings.getPlayerInt();
int monsterint = settings.getMonsterInt();
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setMessage("You have Encountered a Monster");
alertbox.setPositiveButton("Fight!",
new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
createMonster();
fight();
}
});
alertbox.setNeutralButton("Try to Outwit",
new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
// This should not be static
// createTrivia();
trivia();
}
});
// Return to Last Saved CheckPoint
alertbox.setNegativeButton("Run Away!",
new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
runAway();
}
});
// show the alert box
alertbox.show();
// Intellect Check
Button button = ((AlertDialog) alertbox).getButton(AlertDialog.BUTTON_NEUTRAL);
if(monsterint > playerint) {
button.setEnabled(false);
}
}
The line:
Button button = ((AlertDialog) alertbox).getButton(AlertDialog.BUTTON_NEUTRAL);
Gives error:
Cannot cast from AlertDialog.Builder to AlertDialog
How do I fix this?

You can't call getButton() on the AlertDialog.Builder. It has to be called on the resulting AlertDialog after creation. In other words
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
//...All your code to set up the buttons initially
AlertDialog dialog = alertbox.create();
Button button = dialog.getButton(AlertDialog.BUTTON_NEUTRAL);
if(monsterint > playerint) {
button.setEnabled(false);
}
The builder is just a class to make constructing the dialog easier...it isn't the actual dialog itself.
HTH

Better solution in my opinion:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setPositiveButton("Positive", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// some code
}
});
AlertDialog alertDialog = builder.create();
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
if(**some condition**)
{
Button button = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
if (button != null) {
button.setEnabled(false);
}
}
}
});

The trick is that you need to use the AlertDialog object retuned by AlertDialog.Builder.show() method. No need to call AlertDialog.Builder.create().
Example:
AlertDialog dialog = alertbox.show();
if(monsterint > playerint) {
Button button = dialog.getButton(AlertDialog.BUTTON_NEUTRAL);
button.setEnabled(false);
}

Related

The button that I have created does not work. Is there something wrong with my code?

I am building an app in Android studio and basically I want a window to popup when a user clicks the add button. I used the setOnClickListener but when I run the app, nothing happens. Could there possibly something wrong with my code?
Here's my MainActivity code
public class MainActivity extends AppCompatActivity {
Button addBtn;
ListView itemListView;
DatePickerDialog.OnDateSetListener dateSetListener;
String dateString = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addBtn = (Button)findViewById(R.id.addBtn);
itemListView = (ListView)findViewById(R.id.itemListView);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
View view = getLayoutInflater().inflate(R.layout.activity_popup_window, null);
EditText itemName = (EditText)view.findViewById(R.id.itemName);
Button expirationDateBtn = (Button)view.findViewById(R.id.expirationDateBtn);
builder.setView(view)
.setTitle("Add Item")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (itemName.getText().toString().isEmpty() || dateString == null) {
Toast.makeText(MainActivity.this,
"Item name or expiration date is missing",
Toast.LENGTH_LONG).show();
}
else{
//do action
}
}
});
//when clicked on Expiration Date Btn
//display date on button
AlertDialogBuilder doesn't create and show a new AlertDialog implicitly. It only prepares the dialog before explicitly calling create() (or you can directly call show() if you need to display your dialog in the moment it gets built).
Your code misses the following lines at the end of onClick():
AlertDialog dialog = builder.create();
dialog.show();
or just:
builder.show();

Android: What is the best practice to organize methods to show alert dialog

I am beginner in Android development. Suppose I have some methods to show AlertDialog within an Activity. But each AlertDialog behavior is slightly different. What is the best practice to organize the methods to show AlertDiaolog?
code is like this.
private void showNumberPickerDialog() {
LayoutInflater inflater = this.getLayoutInflater();
View numberPickerDialogView = inflater.inflate(R.layout.number_picker, null);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Title for number picker here");
alertDialog.setCancelable(false);
alertDialog.setView(numberPickerDialogView);
final NumberPicker numberPicker = roomSizeNumberDialogView.findViewById(R.id.number_picker);
numberPicker.setMaxValue(10);
numberPicker.setMinValue(0);
numberPicker.setWrapSelectorWheel(false);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Something here
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
private void showMessageDialog(final boolean isA) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Title here");
alertDialog.setCancelable(false);
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (isA) {
doA();
} else {
doB();
}
}
});
alertDialog.show();
}
private void showAlertDialogC() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
final EditText inputEditText = new EditText(this);
inputEditText.setInputType(InputType.TYPE_CLASS_TEXT);
innputEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
alertDialog.setTitle("Title here");
alertDialog.setCancelable(false);
alertDialog.setView(nameEditText);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do something here
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
Is there a good way to organize the parts like this?
You can also use a customizable dialog if that's what you are looking for.
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog_options);
dialog.show();
TextView tvDelete = dialog.findViewById(R.id.tvDelete);
tvDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
Dialog deleteDialog = new Dialog(context);
deleteDialog.setContentView(R.layout.dialog_delete);
deleteDialog.show();
}
});
Treat it just like you would treat an activity. Set onClickListeners on the views for which you want some particular actions. I believe this custom dialog is much more flexible than the AlertDialog
I like to handle my dialog in a separate class, that way you have more control over everything - clickListners, layout design, etc... and you don't have tons of code lines in your activity.
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

Creating ids to implement select listener in dialog

Iam creating a dialog with following code, who creates multiple choice check box.. But I don't know how to create their id's to add click event , I m new to android please help me..:
private void showDailog() {
final String[] items = {" Blue", " Red", " Black", " White", " Pink"};
final ArrayList itemsSelected = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select any theme you want : ");
builder.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int selectedItemId,
boolean isSelected) {
if (isSelected) {
itemsSelected.add(selectedItemId);
} else if (itemsSelected.contains(selectedItemId)) {
itemsSelected.remove(Integer.valueOf(selectedItemId));
}
}
})
.setPositiveButton("Done!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
//Your logic when OK button is clicked
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id)
}
});
dialog = builder.create();
dialog.show();
}
Instead of Alert Dialog create a simple dialog with your custom layout like this
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dialog_lauout);
dialog.show();
Button button = (CheckBox) dialog.findViewById(R.id.button);
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});

How to delete data by selecting a particular button

I am working with android. I want to delete the particular button that i have selected.. I am using onContextItemSelected for selecting the button.What do I write inside
public void onClick(DialogInterface dialog,int id) {} of setPositiveButton??
#Override
public boolean onContextItemSelected(MenuItem item)
{
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
String number;
final Context context = this;
try
{
//number=new ContactListAdapter (this).numberList.get(info.position);
if(item.getTitle()=="View ")
{
Dialog dialog=new Dialog(HubActivity.this);
dialog.setContentView(R.layout.driver_details);
dialog.setTitle("Driver Details");
dialog.show();
}
else if(item.getTitle()=="Edit ")
{
Dialog dialog=new Dialog(HubActivity.this);
dialog.setContentView(R.layout.activity_driver);
dialog.setTitle("Edit Details");
dialog.show();
}
else if(item.getTitle()=="Delete ")
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Delete");
// set dialog message
alertDialogBuilder
.setMessage("Are you sure to delete ?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
//MainActivity.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
If you have defined the button in your xml layout, you cannot delete it but you can remove it from the view by setting (and this is the most common case):
// Button button = findViewById(R.id.button);
button.setVisibility(View.GONE);
The above line will go inside your public void onClick(DialogInterface dialog,int id) {}.
If you have added the button dynamically within the code, you can remove it by getting the parent layout and doing:
ViewGroup.removeView(button);

Dialog box inside tab group not firing

I am having a great difficulty on these part. I cannot call my dialog when I put my class inside Tab Group. Is there anyway I could do this?
This is my dialog creator
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 1:
return createDialog();
default:
return null;
}
}
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case 1:
// Clear the input box.
EditText text = (EditText) dialog.findViewById(TEXT_ID);
text.setText(textme);
text.setKeyListener(null);
break;
}
}
private Dialog createDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(SpecialofMonth.this);
final EditText input = new EditText(this);
input.setId(TEXT_ID);
builder.setView(input);
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
return builder.create();
}
Calling it on button click
View.OnClickListener handlesReadme = new View.OnClickListener() {
public void onClick(View v) {
showDialog(1);
}
};
This one works when it is outside the tab group. But in vice versa or when it is inside, it is not working..
Can you help me out?
in side your TAB Group create like this
AlertDialog.Builder builder = new AlertDialog.Builder(SpecialofMonth.this.getParent());

Categories