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://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4"
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.


No comments:

Post a Comment