How to implement an alert dialog in androidX [duplicate] - java

This question already has answers here:
You need to use a Theme.AppCompat theme (or descendant) with this activity
(63 answers)
Closed 3 years ago.
I have migrated my project to androidX, and I want to implement an alert dialog with positive and negative feedback from the user.
I am using this code:
AlertDialog.Builder builder1 = new AlertDialog.Builder(getApplicationContext());
builder1.setMessage("Write your message here.");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("MSG", "onClick: YES");
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Log.d("MSG", "onClick: No");
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
But I get this error when running the app:
java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

You can use the MaterialAlertDialogBuilder provided by the Material Components library.
Just use:
new MaterialAlertDialogBuilder(context)
.setTitle("Dialog")
.setMessage("Write your message here. ....")
.setPositiveButton("Ok", /* listener = */ null)
.setNegativeButton("Cancel", /* listener = */ null)
.show();
The MaterialAlertDialogBuilder requires a Material theme and will result in an androidx.appcompat.app.AlertDialog.

Related

Define button style for Alert Dialog [duplicate]

This question already has answers here:
How can I change default dialog button text color in android 5
(18 answers)
Closed 3 years ago.
I'm working on an Android App. I have the need to customize Alert Dialog buttons because it shows me the buttons in an unspecified way.
The code to invoke the alert dialogue is:
new AlertDialog.Builder(context,R.style.dialog_theme)
.setTitle(R.string.dialog_title_avviso)
.setMessage(messageResId)
.setPositiveButton(R.string.dialog_button_si, (dialog, which) -> listener.onResponse(dialog, DialogResponse.OK))
.setNegativeButton(R.string.dialog_button_no, (dialog, which) -> listener.onResponse(dialog, DialogResponse.CANCEL))
.show();
In the style.xml I define the following style:
<style name="dialog_theme" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="android:windowTitleStyle">#style/AlertDialogTitleStyle</item>
</style>
I would like to set the dialogue in the following mode:
Any ideas? Thanks
create alert dialog object first, and then use it to change color of text inside button.
CustomDialog builder = new CustomDialog(getActivity(), "Try Again", errorMessage);
AlertDialog dialog = builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
...
}
}).create();
dialog.setOnShowListener( new OnShowListener() {
#Override
public void onShow(DialogInterface arg0) {
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(COLOR.BLUE);
}
});
dialog.show()

How to change the color of buttons in Alert Dialog? [duplicate]

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

Android AlertDialog showing up blank [duplicate]

This question already has an answer here:
Dialog opens blank
(1 answer)
Closed 5 years ago.
I'm trying to make an AlertDialog in onCreateView() inside a Fragment. Here's the code I'm using:
AlertDialog.Builder builder = new AlertDialog.Builder(getContext()));
builder.setTitle("blah blah blah");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//do something
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
getActivity().onBackPressed();
}
});
builder.create().show();
But whenever this executes, I get a completely white dialog where nothing is visible. If I click around the box, I eventually find where the positive button is because the code in setPositiveButton's OnClickListener gets executed. Here's a screenshot:
As you can see, the rest of my app is in the background and I'm left with a useless dialog box. I've tried changing the theme, but that hasn't made any difference. I can't seem to find anyone else with this problem, so any information as to why this is happening is greatly appreciated!
Try this
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AlertStyle);
Add in Style.xml file
<style name="AlertStyle" parent="Theme.AppCompat.Light.Dialog">
<item name="android:colorAccent">#f3f3f3</item>
<item name="android:textColor">#f3f3f3</item>
<item name="android:textColorPrimary">#f3f3f3</item>
</style>
Remove the create() method from the builder.create().show() like that
builder.show();
Try this for all version
AlertDialog.Builder builder;
if(Build.VERSION.SDK_INT >= 21)
builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Light_Dialog_Alert);
else
builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle("title");
builder.setMessage("Message");
builder.create().show();

Button to start activity if statement

I want the button to open a dialog only if the content equals to America. How do I do it?
I've tried creating a dialog activity and then using an intent I got the dialog box but it appeared separately and not over the current activity!
if(check.contentEquals("america")){
// Then I want the dialog to open here
try this:
if(check.contentEquals("america")){
imageview.setAlpha(0);
Intent i = new Intent(ACTION NAME);
startActivity(i);
}
if you want to run a simple dialog all you have to do is:
if(check.contentEquals("america")){
imageview.setAlpha(0);
mDialog.show();
}
to display an alert dialog try this:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle("Title");
builder.setMessage("your message");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
final AlertDialog alert = builder.create();
if(check.contentEquals("america")){
alert.show();
}

How to display AlertDialog in a Fragment?

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

Categories