Kenny Worden
Kenny Worden

Reputation: 4572

Android - Fragment findViewById() always null?

Yes, I realize there are questions VERY similar to this one, but unlike the others, my onCreateView() method inflates the view for the fragment. When I don't use findViewById(), everything inflates and my app works as expected (except for the functionality for the views I want to get in findViewById().

Here is my code:

@Override
public View onCreateView(LayoutInflater p_inflater, ViewGroup p_container, Bundle p_prev_state)
{
    return p_inflater.inflate(R.layout.fragment_main, p_container, false);
}

Whenever I want to access a ListView within my layout, I do this:

private ListView getListView()
{
    return (ListView)getView().findViewById(R.id.main_events);
}

but this is always null. Why? My fragment_main.xml looks like so:

<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:background="@color/white"
    tools:context="me.k.cal.MainActivity$PlaceholderFragment" >

    <ListView android:id="@+id/main_events"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:dividerHeight="1dp"
        android:divider="@color/background_color" />

</RelativeLayout>

My full fragment code can be found here.

Upvotes: 0

Views: 2655

Answers (2)

Pankaj Arora
Pankaj Arora

Reputation: 10274

Use Below Code to inflate your view and get id of listview.

public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {                                                                                                                                                                                                                                                           
    View _view = inflater.inflate(R.layout.fragment1, container, false);

    ListView _list= (ListView) _view.findViewById(R.id.main_events);
    return _view;
}

Upvotes: 5

Mukesh Rana
Mukesh Rana

Reputation: 4091

Try this,hope this helps

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

    ListView eventsList= (ListView) view.findViewById(R.id.main_events);

 return view;

}

Upvotes: 0

Related Questions