gpt4 book ai didi

java - 可以使用哪些不同类型的上下文来代替 Activity ?

转载 作者:行者123 更新时间:2023-11-29 23:05:49 25 4
gpt4 key购买 nike

我正在阅读 admob 中介文档,我看到了这个,但我很困惑,因为我认为当你使用“这个”时,它指的是你正在进行的 Activity 。它说他们建议传递一个 Activity 实例,例如下面。我认为这是唯一可能的方式,有没有人知道我将传递的上下文的示例,而不是我当前的 Activity ?

adView = new AdView(this);

enter image description here

最佳答案

"I was reading through admob mediation documentation and I seen this but im quite confused, because I thought when you use "this" it is referring to the activity you are in."

你有点不对。 this 指的是您当前的对象。来自Java documentation :

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

例如,匿名类中的this会引用对象类:

View view;
view.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
// this will refer to View.OnClickListener object.
}
});

I thought this was the only possible way does anyone know an example of what would be a context I would pass in thats not my current activity ?

您还可以在 Application 类中创建 AdView,但我从来不推荐这样做:

public MyApp extends Application {
private AdView mAdView;

...
public void createAdView() {
// this will refer to MyApp which is a context.
mAdView = new AdView(this);

...
// the rest is history
}
}

或者有人会创建一个 Util 来生成 AdView 但忘记将 Context 限制为仅 Activity:

public AdUtil {
private AdUtil(){}

...

// Here the parameter context can be Application, Activity, etc.
public static AdView createAdView(Context context) {
AdView adView = new AdView(context);

...
return adView;
}
}

关于java - 可以使用哪些不同类型的上下文来代替 Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56570604/

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