gpt4 book ai didi

android - Activityname.this() 和 this 之间有什么区别吗?

转载 作者:太空宇宙 更新时间:2023-11-03 11:50:27 25 4
gpt4 key购买 nike

Activityname.this()this 在安卓中有什么区别吗?

我正在尝试使用对话框中的按钮从同一 Activity 中打开一个 Activity ?我在 Intent 中使用 getApplicationContext()。在某些手机上它可以工作,但在其他手机上它会强制关闭?

ActivityName.thisthis 之间,我应该使用哪一个?为什么?

最佳答案

Is there any difference between Activityname.this() & this in Android ?

这取决于您从哪里调用它。如果您在 Activity 中,而不是在监听器或内部类(如 onCreate)中,则不会。它们都引用 Activity context

如果您说在 onClickListener 内部,那么可以。 this 指的是 listener,你需要使用 ActivityName.this 或类似的东西

someButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
Intent i = (v.getContext(), NextActivity.class); use the button context which will be the same as the activity context
startActivity(i);
}
});

这与使用 DialogAlertDialog 时相同,您需要使用 ActivityName.this

This is an answer它讨论了 Context 的区别,但如果我能找到更好的,我会看看

A great Context explanation

编辑更完整

AFAIK、getApplicationContext()ActivityName.this 适用于 Toastsexample in the docs使用 getApplicationContext()。但是 Toast Docs

Parameters context The context to use. Usually your Application or Activity object.

所以在某些情况下可能会更好,但我一直使用 Activity Context,我想我会一直使用,直到我对此进行更正。

关于android - Activityname.this() 和 this 之间有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18704228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com