Reputation: 88
I have an application in which I frequently use dialogs in all my fragments. I use dialogs in fragmetns mostly for displaying messages from server.
AlertDialog ad = new AlertDialog.Builder(getActivity()).create(); ad.setCancelable(false);
ad.setTitle(title);
ad.setMessage(message);
ad.setButton(context.getString(R.string.text), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
} });
Can I create this is my MainActivty and use this through all my fragments?? Please help me out.
Upvotes: 1
Views: 1339
Reputation: 1977
Please check this
public void showAlert(String title,String message){
AlertDialog ad = new AlertDialog.Builder(this);
ad.create().setCancelable(true).setTitle(title).setMessage(message);
ad.setButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
} });
}
call from fragment
((HomeActivity)getActivity()).showAlert("My title","My Message");
Upvotes: 0
Reputation: 2725
Create a public class as below.
public class UtilsDialog {
public static void promtDialog(Context context,String title, String message){
AlertDialog ad = new AlertDialog.Builder(context).create(); ad.setCancelable(false);
ad.setTitle(title);
ad.setMessage(message);
ad.setButton(context.getString(R.string.text), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
} });
ad.show();
}
}
and call promtDialog method as this in your fragments.
UtilsDialog.promtDialog(getActivity(), "add your title here", "add your message here");
Upvotes: 3
Reputation: 3212
Create a method like :
public void showAlert()
{
AlertDialog ad = new AlertDialog.Builder(getActivity()).create(); ad.setCancelable(false);
ad.setTitle(title);
ad.setMessage(message);
ad.setButton(context.getString(R.string.text), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
} });
}
and call this method wherever required like MainActivity.showAlert();
Upvotes: 1