如何提供使 AlertDialog 按钮起作用的正确上下文

How to supply the right context that will make the button of an AlertDialog to work

开始,我构建了一个 AlertDialog,我可以在我的 Activity 中多次使用它,但我在使用肯定按钮时遇到了问题。 一直在尝试为 (!NetworkCheck.isAvailableAndConnected(getApplicationContext())) { 行提供正确的上下文 在下面的代码中:

主要Activity

public class MainActivity extends AppCompatActivity {

    private final String TAG = "MainActivity";
    private AlertDialog internetDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //The usuals
        Log.d(TAG, "onCreate called");

        internetDialog = new AlertDialog.Builder(MainActivity.this)
                .setTitle(R.string.alert_titl)
                .setCancelable(false)
                .setIcon(R.mipmap.ic_launcher)
                .setMessage(R.string.alert_mess)
                .setPositiveButton(R.string.alert_retry, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (!NetworkCheck.isAvailableAndConnected(getApplicationContext())) {
                            internetDialog.show();
                        } else {
                            getData();
                        }

                    }
                })
                .setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();

                    }
                })
                .create();



        if (NetworkCheck.isAvailableAndConnected(this)) {

              getData();

              } else {
                  internetDialog.show();
              }
          }


    //This method will get data from the web api

    private void getData(){


        Log.d(TAG, "getData called");
        //Showing progress dialog
        mProgressDialog = new ProgressDialog(MainActivity.this);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setMessage(this.getResources().getString(R.string.load_post));
        mProgressDialog.show();


        //Creating a json request
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigPost.GET_URL,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, "onResponse called");
                        //Dismissing the progress dialog
                        if (mProgressDialog != null) {
                            mProgressDialog.hide();
                        }
                        /*progressDialog.dismiss();*/


                        //calling method to parse json array
                        parseData(response);

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        if (mProgressDialog != null) {
                            mProgressDialog.hide();
                        }

                    }
                });

        //Creating request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        //Adding request to the queue
        requestQueue.add(jsonArrayRequest);

    }

网络检查

public class NetworkCheck {

    public static boolean isAvailableAndConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        boolean isNetworkAvailable = cm.getActiveNetworkInfo() != null;
        boolean isNetWorkConnected = isNetworkAvailable && cm.getActiveNetworkInfo().isConnected();

        return isNetWorkConnected;

    }

}

负号按钮工作正常,但正号按钮只能成功关闭对话框。 getData 不会被调用(如果有互联网连接)也不会再次显示对话框(如果没有互联网连接)。 请提供给 (!NetworkCheck.isAvailableAndConnected(getApplicationContext())) { 以使肯定按钮起作用的正确上下文(如果这是问题所在)是什么?我尝试了 getApplicationContextgetBaseContextMainActivity.this,但没有用。

如果我这样做:

if (NetworkCheck.isAvailableAndConnected(this)) {

            //Caling method to get data
            getData();
        } else {
            final Context mContext;
            mContext = this;
            final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
            alertDialogBuilder.setTitle(R.string.alert_titl);
            alertDialogBuilder.setCancelable(false);
            alertDialogBuilder.setIcon(R.mipmap.ic_launcher);
            alertDialogBuilder.setMessage(R.string.alert_mess);
            alertDialogBuilder.setPositiveButton(R.string.alert_retry, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (!NetworkCheck.isAvailableAndConnected(mContext)) {
                        alertDialogBuilder.show();
                    } else {
                        getData();
                    }


                }
            });
            alertDialogBuilder.setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();

                }
            });
            alertDialogBuilder.show();

        }

如果有 Internet 连接,重试按钮会调用 getData,如果没有连接,则重新显示对话框。

我本可以使用这种方法,但如果我愿意,我无法用其他方法显示对话框。

我无法发表评论,所以需要在回答中添加。 注意你的比赛有误,你可以使用 getBaseContext()。在你的情况下,只有当你的互联网连接时才能调用 getdata(),你可以尝试连接互联网并单击它现在应该调用 getdata() 的肯定按钮。我检查过它工作正常。其次,我的假设是,如果仍然断开互联网连接,您希望阻止对话框在单击肯定按钮时关闭。标准略有不同。

将您的代码更改为此

AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Message");
        builder.setPositiveButton("OK",
                new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        //Do nothing here because we override this button later to change the close behaviour.
                        //However, we still need this because on older versions of Android unless we
                        //pass a handler the button doesn't get instantiated
                    }
                }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });

        internetDialog = builder.create();
        internetDialog.show();
        internetDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                boolean test = NetworkCheck.isAvailableAndConnected(getBaseContext());
                        if (test) {
                            getData();
                            internetDialog.dismiss();
                        }
                //else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
            }
        });
enter code here

您可能看过以下详细答案。 或者更好地使用自定义对话框。 :)

希望您已将这两行添加到您的清单文件中。

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

好的,我还没有发表评论的权利,我正在回答section.Below答案一定会解决你的问题,请试试看:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    //The usuals
    Log.d(TAG, "onCreate called");

    showDialog();


    if (NetworkCheck.isAvailableAndConnected(MainActivity.this)) {

        getData();

    } else {
        internetDialog.show();
    }

}

private void showDialog() {
    internetDialog = new AlertDialog.Builder(MainActivity.this)
            .setTitle(R.string.alert_titl)
            .setCancelable(false)
            .setIcon(R.mipmap.ic_launcher)
            .setMessage(R.string.alert_mess)
            .setPositiveButton(R.string.alert_retry, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (!NetworkCheck.isAvailableAndConnected(MainActivity.this)) {
                        if (internetDialog != null && internetDialog.isShowing()) {
                            internetDialog.dismiss();
                            internetDialog = null;
                            showDialog();
                            internetDialog.show();
                        }
                    } else {
                        getData();
                    }

                }
            })
            .setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();

                }
            })
            .create();


}

//This method will get data from the web api

private void getData(){


    Log.d(TAG, "getData called");
    //Showing progress dialog
    mProgressDialog = new ProgressDialog(MainActivity.this);
    mProgressDialog.setCancelable(false);
    mProgressDialog.setMessage(this.getResources().getString(R.string.load_post));
    mProgressDialog.show();


    //Creating a json request
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigPost.GET_URL,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, "onResponse called");
                    //Dismissing the progress dialog
                    if (mProgressDialog != null) {
                        mProgressDialog.hide();
                    }
                    /*progressDialog.dismiss();*/


                    //calling method to parse json array
                    parseData(response);

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if (mProgressDialog != null) {
                        mProgressDialog.hide();
                    }

                }
            });

    //Creating request queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    //Adding request to the queue
    requestQueue.add(jsonArrayRequest);

}