简体   繁体   中英

How to findViewById in a Fragment from another layout, not the one inflated as the root layout?

I am using a Fragment with a ViewPager, I need to set text in the ViewPager from my fragment but I am unable to, as I a keep getting:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

This is how I have initialized the TextViews from the ViewPager's XML file:

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;

It's not possible to directly access from child layout. A simple way is using interfaces. You can define an interface in Fragment constructor then implement it in root Fragment which hosts viewPager.

interface SomeInterface
{
public void callback (Type xxx)
}

Parent fragment must implement interface to listen any callBack

 ParentFragment implements SomeInterface
    {
    ...
         @override
         public void callBack(Type xxx)
         {
                //Change view pager 
         }
    }

and then pass this fragment as a listener in your viewpager constructor and childFragment constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM