You can place a generic method in a separate class and just pass in the id of the layout you wish to use, such as:
/**
* makeAlertBox
*
* Populates an Android OS alert dialog with the passed params.
* Only for quick messages that require no imput, other than to
* dismiss the dialog
*
* @param context - The application context
* @param title - The dialog's title
* @param message - The dialog's message
* @param positiveText - The OK buttons text
*/
public static void makeAlertBox(Context context, String title, String message,
String positiveText, int layoutId)
{
try
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(layoutId, null);
new AlertDialog.Builder(context)
.setView(view)
.setTitle(title)
.setMessage(message)
.setPositiveButton(positiveText, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
})
.setCancelable(false)
.show();
}
catch(Exception ex)
{
Log.e("UTIL", "Caught exception while attempting to create alertdialog");
ex.printStackTrace();
}
}
In my code my abstract class is called Utility
So I'd call:
Utility.makeAlertBox(getApplicationContext(), "Title", "Message", "Okay!", someLayoutId);
edit You can obviously get rid of the extra parameters that you don't need. I mearly copied and pasted from my workspace, as an example.
edit 2 If you plan on using this code anywhere other than an Activity, you're going to need a reference to the Context/Application. Your best bet is to use a Singleton class, that inherits from the Application class, like so:
public class myApplication extends Application
{
private static myApplication instance;
@Override
public void onCreate()
{
instance = this;
super.onCreate();
}
/**
* getInstance
* @return Returns the instance of this myApplication
*/
public static myApplication getInstance()
{
if(instance != null)
return instance;
return new myApplication();
}
}
Then when you need to access the context you can do: myApplication.getInstance()
Or myApplication.getInstance().getApplicationContext()
You'll also need to update your Manifest to ensure the application is picked up:
<application
android:name="com.YOURPACKAGE.myApplication"
<!-- everything else. Such as Activites etc...-->
</application
Hope this helps.