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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:29:52  来源:igfitidea点击:

Why am I getting "The method getContext() is undefined for the type MainActivity"?

javaandroid

提问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 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 MainActivtyextends Activty, then just use parentas the context:

如果MainActivtyextends 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.thisif it's within an inner class.

它应该是this,或者MainActivty.this如果它在内部类中。