您可以將一個通用的方法在一個單獨的類,只是傳遞要使用,如佈局ID:
/**
* 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();
}
}
在我的代碼我的抽象類被稱爲Utility
所以我打電話:
Utility.makeAlertBox(getApplicationContext(), "Title", "Message", "Okay!", someLayoutId);
編輯你可以明顯地擺脫你不需要額外的參數。作爲一個例子,我從工作區中複製粘貼。
編輯2如果您計劃在活動以外的任何地方使用此代碼,您將需要對上下文/應用程序的引用。最好的辦法是使用Singleton類,繼承從應用程序類,如下所示:
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();
}
}
然後,當你需要訪問的背景下,你可以這樣做:myApplication.getInstance()
或者myApplication.getInstance().getApplicationContext()
你也需要更新您的清單,以確保應用程序被拿起:
<application
android:name="com.YOURPACKAGE.myApplication"
<!-- everything else. Such as Activites etc...-->
</application
希望這會有所幫助。
所以你的意思是先生我會創建一個新班級? – user3698267 2015-01-15 15:56:09
你不需要。但從長遠來看,重構它自己的對象會更好,特別是如果它只是一個對話框而不是真的需要在一個活動中。創建一個新的抽象類並添加此方法(將其更改爲您認爲合適的方式),然後按照上面顯示的名稱(將Utility替換爲您自己的類名稱)調用它。 – LokiSinclair 2015-01-15 16:00:29
sir ive getApplicationContext出錯。 – user3698267 2015-01-15 16:15:50