java 为什么我收到“未定义 MainActivity 类型的 getContext() 方法”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16621136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why am I getting "The method getContext() is undefined for the type MainActivity"?
提问by Osman
My MainActivity extends activity and I use getContext()
in another class that has a instance of MainActivity passed in and it works fine there, my code:
我的 MainActivity 扩展了活动,我getContext()
在另一个类中使用了一个传入 MainActivity 实例的类,它在那里工作正常,我的代码:
convertView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.nowview, parent, false);
Class constructor:
类构造函数:
public PictureCard(String url, String title, int index,
int pos, MainActivity parent)
{
this.parent = parent;
// ...
}
How I call the class
我如何称呼班级
Card newCard = new PictureCard(links.get(index) , titles.get(index),
index, position, parent);
(Parent is passed in as this from the MainActivity class)
(父类是从 MainActivity 类传入的)
回答by paulsm4
Have you tried using getApplicationContext()
instead of getContext()
?
您是否尝试过使用getApplicationContext()
代替getContext()
?
These links might help:
这些链接可能会有所帮助:
http://developer.android.com/reference/android/app/Activity.html
http://developer.android.com/reference/android/app/Activity.html
getApplication() vs. getApplicationContext()
getApplication() 与 getApplicationContext()
Difference between getContext() , getApplicationContext() , getBaseContext() and "this"
getContext() 、 getApplicationContext() 、 getBaseContext() 和“this”之间的区别
回答by stinepike
Instead of passing MainActivity you can pass context as parameter lik this
您可以将上下文作为参数传递,而不是传递 MainActivity
public PictureCard(String url, String title, int index, int pos, Context parent)
and call like
并打电话给
Card newCard = new PictureCard(links.get(index) , titles.get(index), index, position, MainActivity.this);
回答by Eng.Fouad
If MainActivty
extends Activty
, then just use parent
as the context:
如果MainActivty
extends Activty
,则仅用parent
作上下文:
convertView = LayoutInflater.from(parent)
.inflate(R.layout.nowview, parent, false);
Also, I suspect that you're passing the wrong instance here:
另外,我怀疑您在这里传递了错误的实例:
Card newCard = new PictureCard(links.get(index) , titles.get(index),
index, position, parent);
^^^^^^
it should be this
, or MainActivty.this
if it's within an inner class.
它应该是this
,或者MainActivty.this
如果它在内部类中。