Adnan Arshad
Adnan Arshad

Reputation: 150

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;

Upvotes: 0

Views: 176

Answers (1)

Steve
Steve

Reputation: 79

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.

Upvotes: 1

Related Questions