从另一个 Activity 中的 onClick 按钮调用另一个 class 中的 AlertDialog

Calling an AlertDialog in another class from a button onClick in another Activity

我想通过按钮 onClick 事件从 AccountManager.class 调用 Alerts.class 中的 AlertDialog "DeleteConfirm"。如何在不影响 AlertDialog 从我的数据库中删除条目的能力的情况下解决这个问题。

编辑:我之前曾尝试调用 Alerts.DeleteConfirm(con, acc); 并分别以 "Cannot resolve method con and acc" 结束。如果有人可以告诉我如何正确地将 conacc 传递到应该修复它的 onClickListener 中。

如果有任何代码缺失供参考,请随时询问。

AlertDialog "DeleteConfirm" 片段:

public class Alerts extends Activity {



public static void ShowAccAddedAlert(Context con)
{
    AlertDialog.Builder builder=new AlertDialog.Builder(con);
    builder.setTitle("Add new Account");
    builder.setIcon(android.R.drawable.ic_dialog_info);
    DialogListener listener=new DialogListener();
    builder.setMessage("Account Added successfully");
    builder.setPositiveButton("ok", listener);

    AlertDialog diag=builder.create();
    diag.show();
}

public static AlertDialog DeleteConfirm(final Context con, final Account Acc) {


    AlertDialog.Builder b = new AlertDialog.Builder(con);
    b.setTitle("Account Details");
    LayoutInflater li = LayoutInflater.from(con);
    View v = li.inflate(R.layout.delete, null);
    b.setView(v);

    b.setPositiveButton("Yes", new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            DatabaseHelper db = new DatabaseHelper(con);
            db.DeleteAcc(Acc);
        }
    });

    b.setNegativeButton("No", null);

    return b.create();

    }
}

AccountManager 按钮 onClick 片段:

public class AccountDetails extends Activity {


@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.accdetails);

 Button delete = (Button) findViewById(R.id.delete);
    delete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //THIS IS WHERE I WANT TO CALL MY DeleteConfirm AlertDialog
        }
    });
  }
}

delete.OnClickListener() 中调用 Alert.DeleteConfirm(con, acc); 并将 (con, acc) 替换为 (your_class'_context, object_of_Account_class)

更好的方法,创建一个 java class (Utility.java),在那里编写您的 DeleteConfirm(Context context) 方法并从两个活动中调用它。

创建 Util.java plain java class,粘贴下面的代码,

public static void alertDialogShow(Context context, String message)
        {
            final AlertDialog alertDialog = new AlertDialog.Builder(context).create();
            alertDialog.setMessage(message);
            alertDialog.setButton("OK", new DialogInterface.OnClickListener() 
            {
                public void onClick(DialogInterface dialog, int which) 
                {
                    alertDialog.dismiss();
              } 
            }); 
            alertDialog.show();
        }

现在来自您的活动电话

Utils.alertDialogShow(MyActivity1.this,"Alert Message 01");

Utils.alertDialogShow(MyActivity2.this,"Alert Message 02");