ViewPager - 从活动更新片段片段、ViewPager

2023-09-12 05:41:51 作者:失我者永失

我有3个片段一个ViewPager。从网站并将结果显示在TextViews一个片段下载数据。现在,当用户点击该项目的MainActivity的菜单中选择刷新,该片段应重新下载数据并显示。 我试图创建在片段的类的函数刷新,并从MainActivity菜单调用它。这工作,但随后崩溃,因为应用程序无法找到的TextView。变量视图是空的,它会导致空指针异常。

I have a ViewPager with 3 fragments. One fragment downloads data ​from a website and displays it in TextViews. Now when the user clicks in the menu of the MainActivity on the item "refresh", the fragment should redownloads the data and displays it. I tried to create a function refresh in the fragment's class and call it from the MainActivity's menu. That worked, but then it crashes because the app can't find the textview. The variable view is empty and it causes a null pointer exception.

我能做些什么来解决这个?

What can I do to resolve this?

非常感谢!

推荐答案

从你的fragmentactivity,

From your fragmentactivity,

Fragment tehFraggerz = getSupportFragmentManager().findFragmentByTag(string);

其中字符串是标签。您可以设置在添加片段的标记,更换等方法。

where string is the tag. You set the tag of the fragments in the add, replace, etc methods.

一旦你有你的片段,你可以做

Once you have your fragment, you can do

TextView tehTexterz = (TextView) tehFraggerz.getView().findViewById(R.id.tehText);