igorfeiden
igorfeiden

Reputation: 177

My findViewById() returns null, but it shouldn't

My findViewById returns null, but it shouldn't. As you'll see, the button is in the same XML file.

And calling getActivity() makes no difference at all

Here's my onCreateView:

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

    Button  request = (Button) getView().findViewById(R.id.button_request);

    return rootView;
    }

And here's my fragment_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container_relative"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    tools:context="br.com.igor.MainActivity$PlaceholderFragment" >

    <TextView
        android:id="@+id/servic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:layout_marginBottom="0dp"
        android:paddingTop="15dp"
        android:text="Sample instructions" />

    <Button
        android:id="@+id/button_request"
        style="@style/button_default"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="15dp"
        android:layout_below="@id/servic"
        android:text="Request" />

</RelativeLayout>

Upvotes: 1

Views: 52

Answers (1)

Blackbelt
Blackbelt

Reputation: 157437

getView is returning null, not findViewById. Use rootView in place of getView

  Button  request = (Button) rootView.findViewById(R.id.button_request);

getView returns the view you inflated in onCreateView

Upvotes: 3

Related Questions