如何在 Android 的非活动类中编写自定义警报?
Posted
技术标签:
【中文标题】如何在 Android 的非活动类中编写自定义警报?【英文标题】:How to write a Custom Alert inside a Non activity class in Android? 【发布时间】:2021-09-10 09:49:37 【问题描述】:我必须在非活动类上编写一个自定义警报,以从所有活动中显示这一点。 我已将充气机用于自定义警报,但它会使应用程序崩溃。请参阅下面的代码。请为此提出解决方案
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;
);
【问题讨论】:
【参考方案1】:试试下面的代码,它会对你有所帮助。
//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();
【讨论】:
以上是关于如何在 Android 的非活动类中编写自定义警报?的主要内容,如果未能解决你的问题,请参考以下文章