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

时间:2015-02-28 15:34:54

标签: android sqlite android-alertdialog buttonclick

我想打电话给我的AlertDialog" DeleteConfirm"在我的AccountManager.class的Alerts.class中通过按钮onClick事件。如何在不影响AlertDialog从数据库中删除条目的能力的情况下进行此操作。

编辑:我之前尝试过调用Alerts.DeleteConfirm(con, acc);并最终得到一个"无法解决方法conacc"分别。如果有人可以告诉我如何正确地将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
        }
    });
  }
}

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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

创建Util.java普通java类,在那里粘贴代码,

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");