[英]How to findViewById in a Fragment from another layout, not the one inflated as the root layout?
我正在使用带有 ViewPager 的片段,我需要从我的片段中设置 ViewPager 中的文本,但我无法这样做,因为我不断得到:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
这就是我从 ViewPager 的 XML 文件中初始化 TextView 的方式:
View root = inflater.inflate(R.layout.fragment_library, container, false);
.
.
contentHeading = root.findViewById(R.id.content_heading);
contentBody = root.findViewById(R.id.content_body);
.
.
return root;
无法直接从子布局访问。 一种简单的方法是使用接口。 您可以在 Fragment 构造函数中定义一个接口,然后在承载 viewPager 的根 Fragment 中实现它。
interface SomeInterface
{
public void callback (Type xxx)
}
父片段必须实现接口来监听任何回调
ParentFragment implements SomeInterface
{
...
@override
public void callBack(Type xxx)
{
//Change view pager
}
}
然后将此片段作为侦听器传递到您的 viewpager 构造函数和 childFragment 构造函数中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.