Search code examples
androidandroid-fragmentsandroid-linearlayoutlayout-inflaterandroid-scrollview

Why LinearLayout inside ScrollView of a Fragment is NULL object?


I am trying to add multiple views to the Fragment dynamically:

@Override
    public View onCreateView(LayoutInflater inflater, 
    ViewGroup container, Bundle savedInstanceState) {


     ViewGroup vg = (ViewGroup) inflater.inflate(R.layout.fragment1, container, false);
     ViewGroup parent = (ViewGroup) getActivity().findViewById(R.id.linearLayoutOfFirstFragment);
     if (parent==null) 
     Toast.makeText(getActivity(), 
            "Null object " , 
            Toast.LENGTH_SHORT).show(); //findViewById(R.id.linearLayoutOfFirstFragment);
     myFirstView= (TextView)inflater.inflate(R.layout.mytextview, container, false);
     vg.addView(myFirstView);
     /*mySecondView= (TextView)inflater.inflate(R.layout.mytextview, container, false);
     parent.addView(mySecondView);

......

XML for Fragment 1 - fragment1.xml:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
>
<LinearLayout 
  android:id="@+id/linearLayoutOfFirstFragment"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:background="#00FF00"/>
</ScrollView>

I could add it to the fragment when the top layout was Linear Layout. However when tried to add it to the Linear Layout inside scroll View after inflating it, get Linear Layout object NULL. Should I inflate Linear Layout as well, to be able to add to it ? HOW TO DO IT? Thank you in advance.


Solution

  • Change

    ViewGroup vg = (ViewGroup) inflater.inflate(R.layout.fragment1, container, false);
    ViewGroup parent = (ViewGroup) getActivity().findViewById(R.id.linearLayoutOfFirstFragment);
    

    with

    ViewGroup vg = (ViewGroup) inflater.inflate(R.layout.fragment1, container, false);
     ViewGroup parent = (ViewGroup) vg.findViewById(R.id.linearLayoutOfFirstFragment);
    

    Since linearLayoutOfFirstFragment is inside fragment1 you have to retrieve it through vg