Android-初学者的警报对话

Alert Dialogue in Android-beginners

我正在尝试创建一个简单的警报对话框,我正在按照此 link 中的步骤操作 但是,我收到错误消息:getActivity() can't be resolved 经过一番搜索,我了解到 getActivity() 可以由用户定义,但我不确定我应该怎么做。

这是我的资料:

public void about(View v1) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Add the buttons
        builder.setNeutralButton(R.string.close, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                finish();//go to the previous activity
            }
        });
        
// Set other dialog properties
        builder.setMessage(R.string.myName);

// Create the AlertDialog
        AlertDialog dialog = builder.create();}

getActivity()是获取Activity的片段方法。 如果您在 activity 中,您只需将其替换为 YourActivityClassName.this

// in a fragment
    new AlertDialog.Builder(getContext())
                            .setTitle("Alert title")
                            .setMessage("Alert Message")
                            .setCancelable(false)
                            .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            }).show();