44

If I try to inflate a view within a fragment I am getting NULL.. For example:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Here I will inflate my view using the layout ID & return.
    return view;
}

Whenever a button is clicked I need to create a dynamic view e.g.: button & add to the LinearLayout. I would like to perform this operation inside my fragment class like this:

public void addPlaces() {    
    Button button = new Button(null);
    button.setText("button name");
    // e.g. like adding button to enter code here linear layout
    linearLayout.addView(button); 
}

So, if I get inflate LinearLayout inside onCreateView and use it in add class, I'm getting NULL. How to achieve?

JJD
  • 50,076
  • 60
  • 203
  • 339
Naruto
  • 9,476
  • 37
  • 118
  • 201

1 Answers1

76

Declare the variable as a instance variable and then initialize Linear Layout

LinearLayout linearLayout;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment1, container, false);
    linearLayout = (LinearLayout) rootView.findViewById(R.id.linearlayout);
    return rootView;
}

Then

public void addPlaces() {
    Button button = new Button(getActivity());
    // needs activity context
    // fragment hosted by a activity. use getActivity() to get the context of the hosting activity. 
    button.setText("button name");
    linearlayout.addView(button);
}

Example: Modify the below according to your requirement.

fragment1.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Button" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:id="@+id/linearlayout"
        android:layout_height="fill_parent"
        android:layout_above="@+id/button1"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:orientation="vertical" >
    </LinearLayout>

</RelativeLayout>

Myfragment.java

public class Myfragment extends Fragment {

    LinearLayout linearLayout;
    View rootView;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Button b = (Button) rootView.findViewById(R.id.button1);
        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                addPlaces();
            }

        });
        linearLayout = (LinearLayout) rootView.findViewById(R.id.linearlayout);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment1, container, false);
        return rootView;
    }

    public void addPlaces() {
        Button button = new Button(getActivity()); // needs activity context
        button.setText("button name");
        linearLayout.addView(button);
    }
}

Snap shot of my emulator

enter image description here

Edit :

activity-main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

     <fragment android:name="com.example.fragments.Myfragment"
            android:id="@+id/frag"
            android:layout_above="@+id/button1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />

      <Button
          android:id="@+id/button1"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_alignParentBottom="true"
          android:layout_centerHorizontal="true"
          android:text="Button" />

</RelativeLayout>

MainActivity.java

public class MainActivity extends FragmentActivity {
    Button b;
    Myfragment fragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragment = new Myfragment();
        fragmentTransaction.add(R.id.frag, fragment);
        fragmentTransaction.commit();
        b = (Button) findViewById(R.id.button1);
        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                fragment.addPlaces();
            }

        });
    }
}

Myfragment.java

public class Myfragment extends Fragment {

    LinearLayout linearLayout;
    View rootView;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        linearLayout = (LinearLayout) rootView.findViewById(R.id.linearlayout);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment1, container, false);
        return rootView;
    }

    public void addPlaces() {
        Button button = new Button(getActivity()); // needs activity context
        button.setText("button name");
        linearLayout.addView(button);
    }
}
alexgophermix
  • 4,189
  • 5
  • 32
  • 59
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • Hi, if i call GRPlacesFragment grplaces = new GRPlacesFragment(); getSupportFragmentManager().beginTransaction().add(R.id.myresqplaces, grplaces).commit(); grplaces.addPlaces(this); if i do like this my control is not at all hitting oncreateview method. – Naruto Jul 11 '13 at 17:52
  • @ll no need to pass `this` `getActivity()` is enough. – Raghunandan Jul 11 '13 at 18:02
  • Definitely,i am calling from fragmentactivity, so i will try your code now – Naruto Jul 11 '13 at 18:02
  • Hi i have a doubt, instead of fragment can we use framelayout? – Naruto Jul 11 '13 at 18:26
  • http://stackoverflow.com/questions/12114015/trying-to-add-a-fragment-to-my-fragment-container-framelayout. http://stackoverflow.com/questions/6185272/android-honeycomb-how-to-change-fragments-in-a-framelayout-without-re-creating. yes it is possible. one more here http://stackoverflow.com/questions/15492717/get-fragment-dynamically-attached-to-framelayout. search on so there are lots of similar posts – Raghunandan Jul 11 '13 at 18:32
  • I was doing one mistake, i was calling add very next to the commit of fragment transaction, that is the reason i was getting failed. Oncreateview method of fragment will get called once oncreateactivity scope is completed. but i'm not understanding why?. oncreateview method of fragment will not get called on creating the object.. THanks lot for your help.. – Naruto Jul 11 '13 at 19:09
  • @LLL Move your initialization to `onActivityCreated` then it will work – Raghunandan Jul 12 '13 at 03:10