[英]How to write a Custom Alert inside a Non activity class in Android?
我必須在非活動類上編寫自定義警報,以從所有活動中顯示該警報。 我已將 inflater 用於自定義警報,但它使應用程序崩潰。 請參閱下面的代碼。請為此提出一個解決方案
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
// LayoutInflater inflater = context.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alertlayout, null);
dialogBuilder.setView(dialogView);
dialogBuilder.setCancelable(false);
TextView btn_ok = dialogView.findViewById(R.id.btn_ok);
TextView txt_dia = dialogView.findViewById(R.id.txt_dia);
txt_dia.setText(msg);
if(subAlertDialog != null && subAlertDialog.isShowing()) {
return;
}
subAlertDialog = dialogBuilder.create();
subAlertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
subAlertDialog.show();
btn_ok.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
subAlertDialog.dismiss();
return false;
}
});
試試下面的代碼,它會幫助你。
//Call dialog from activity
CustomDialog.showDialog(this);
//This is your custom dialog class
public class CustomDialog {
public static void showDialog(Context context){
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View dialogView = inflater.inflate(R.layout.alertlayout, null);
dialogBuilder.setView(dialogView);
dialogBuilder.setCancelable(false);
TextView btn_ok = dialogView.findViewById(R.id.btn_ok);
TextView txt_dia = dialogView.findViewById(R.id.txt_dia);
txt_dia.setText("abc");
btn_ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
dialogBuilder.create().show();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.