Search code examples
androidandroid-activitynullreferenceexceptionfragment

findViewById returns NULL when using Fragment


I'm new to Android developing and of course on Fragments.

I want to access the controls of my fragment in main activity but 'findViewById' returns null. without fragment the code works fine.

Here's part of my code:

The fragment:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    tools:ignore="HardcodedText" >

    <EditText
        android:id="@+id/txtXML"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:ems="10"
        android:scrollbars="vertical">
    </EditText>

</LinearLayout>

the onCreate of MainActivity:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.main);

        this.initialisePaging();

        EditText txtXML = (EditText) findViewById(R.id.txtXML);}

on this point the txtXML is null.

What's Missing in my code or what should I do?


Solution

  • You should inflate the layout of the fragment on onCreateView method of the Fragment then you can simply access it's elements with findViewById on your Activity.

    In this Example my fragment layout is a LinearLayout so I Cast the inflate result to LinearLayout.

        public class FrgResults extends Fragment 
        {
            public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
            {
                //some code
                LinearLayout ll = (LinearLayout)inflater.inflate(R.layout.frg_result, container, false);
                //some code
                return ll;
            }
        }