Java Android:如何在 OnItemClickListener() 中调用 getActivity()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20540773/
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-08-13 02:38:27  来源:igfitidea点击:

Android: How to call getActivity() in OnItemClickListener()?

javaandroidcastingonitemclickmain-activity

提问by user2212461

I am trying to call getActivity() in the OnItemClickListener:

我正在尝试在 OnItemClickListener 中调用 getActivity():

class ViewTest{ //called in a fragment
setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int p, long i) {
                ((MainActivity) getActivity()).makeResultsbarVisible();
...
            }

        });

}

}

In the fragment, the class is instantiated as:

在片段中,类被实例化为:

ViewTest editTest = new ViewTest(this);

But I get an error that I cannot fix:

但是我收到一个无法修复的错误:

The method getActivity() is undefined for the type new AdapterView.OnItemClickListener(){}

How can I call getActivity inside onItemClick()? Thanks.

如何在 onItemClick() 中调用 getActivity?谢谢。

采纳答案by Apoorv

You can only use getActivityinside a Fragmentclass or one extending it. If your onItemClickListeneris in an Activityuse MainActivity.this

您只能getActivityFragment类中使用或扩展它。如果您onItemClickListener正在Activity使用MainActivity.this

回答by Mitesh Shah

Use Class_name.thisor define a Contextvariable. and then call your makeResultsbarVisible()by using Contextvariable,

使用Class_name.this或定义一个Context变量。然后makeResultsbarVisible()使用Context变量调用你的,

Like,

喜欢,

Context c = this;

c.makeResultsbarVisible();