android - 为什么要在 AlertDialog.Builder 参数中添加类名?

标签 android android-activity android-alertdialog

AlertDialog.Builder 构造函数将 Context 作为其参数:

AlertDialog.Builder (Context上下文),

我发现了一个例子,其中参数不仅是 this 而是:

new AlertDialog.Builder(MyClassName.this);

为什么?

此外,我已经在 Activity 中看到过这个东西,这次我们将 .class 添加到我们尝试访问的 Activity 的名称中。您能告诉我这两个关键字的含义吗?

非常感谢

最佳答案

Activity 类是 Context 的子类,因此您可以在示例中将其用作参数。 现在,例如,如果您在 onClick 方法(即按钮)或内部类或异步任务中,使用“this”不会引用 Activity 本身,因此您需要使用 YourActivity.this。

相反,当您看到 ClassName.class 时,通常是因为您需要指定要启动的 Activity 、服务或任何内容,在这种情况下,参数类型是 Class。 例如,如果你想开始一个 Activity ,你可以使用:

Intent intent = new Intent(this or ActivityName.this, AnotherActivityName.class);

例如:

public class MyActivity extends Activity {
....

@Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        // in this case 'this' refers the current activity instance
        // (but of course you can also use MyActivity.this
        myAdapter = new ArrayAdapter(this, R.layout.list_item, items);

        ...

        myButton.setOnClickListener(new OnClickListener() {
             @Override
                 public void onClick(View arg0) {
                     // here you must use ActivityName.this because
                     // 'this' refers to the OnClickListner instance
                     Intent intent = new Intent(ActivityName.this, AnotherActivityNameActivityName.class);
                     startActivity(intent);
                 }
        });

        ...
}

关于android - 为什么要在 AlertDialog.Builder 参数中添加类名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8498944/

相关文章:

android - 是否可以转储设备硬件配置文件以创建等效的 AVD?

android - 从 Google Play 游戏 API 获取用户 ID?

android - 带有监听器的通用 DialogFragment

android - 无法单独获取选定的叠加值

java - 具有自定义内容 View 的 AlertDialog 看起来与 AlertDialog 完全不同

android - 如何在将数据设置为 edittext 时禁用 TextWatcher

java - 如何在android中制作一个没有控件的相机应用程序,以便屏幕上只显示镜头的 View ?

java - 为什么淡入淡出 Activity 转换只能使用 Handler 而不能使用 Thread?

java - 单击按钮时出现 Intent 错误 - 为什么?

android - 关闭对话框 Android