java 如何从 Android 中的 Fragment 调用 ArrayAdapter 构造函数

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

how to call ArrayAdapter constructer from Fragment in Android

javaandroidlistviewandroid-arrayadapter

提问by Arif YILMAZ

I am trying to add a two-column ListView to my android app. When I created the project, I selected the option Fragment which creates that beautiful navigation by sliding to left and right. So my MainActivityextends FragmentActivity.

我正在尝试向我的 android 应用程序添加一个两列 ListView。当我创建项目时,我选择了选项 Fragment,它通过向左和向右滑动来创建漂亮的导航。所以我的MainActivity扩展FragmentActivity

my problem is when I am trying to add AddayAdapter to ListView, the construstor of ArrayAdapter looks for a context object and I dont know to pass that.

我的问题是当我尝试将 AddayAdapter 添加到 ListView 时,ArrayAdapter 的构造函数会查找上下文对象,但我不知道要传递它。

here is the code where I get error

这是我出错的代码

StableArrayAdapter adapter = new StableArrayAdapter(this, R.layout.row , list);
listview.setAdapter(adapter);

When I pass "this", it passes FragmentActivity because the activity extends FragmentActivity. but constructor need a "Context" object.

当我传递“this”时,它传递 FragmentActivity,因为该活动扩展了 FragmentActivity。但是构造函数需要一个“上下文”对象。

it gives this error message

它给出了这个错误信息

"The constructor MainActivity.StableArrayAdapter(MainActivity.DummySectionFragment, int, ArrayList<String>) is undefined"

How can I pass Context object?

如何传递 Context 对象?

回答by Neoh

You are setting the adapter inside a fragment. Use

您正在片段内设置适配器。利用

StableArrayAdapter adapter = new StableArrayAdapter(this.getActivity(), R.layout.row , list);

回答by Thalaivar

StableArrayAdapter adapter = new StableArrayAdapter(getContext(), R.layout.row , list);
listview.setAdapter(adapter);

Did you try passing something like this from your Fragment. Try either getContext()or getApplicationContext().

你有没有尝试从你的 Fragment 传递这样的东西。尝试getContext()getApplicationContext()