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/