Note that there are some explanatory texts on larger screens.

plurals
  1. POHow/When do I initialize a Fragment added via XML?
    text
    copied!<p>I have a 2 pane view that is defined in XML. For xlarge, the left side of the view is a Fragment that deals with content selection. I want to initialize this selector <code>ListFragment</code> to have the first item highlighted on app start up.</p> <p>I've written a method in the <code>ListFragment</code> to do this:</p> <pre><code>public void setSelectedItem (int position) { //Unselect the previous item if(mPreviousPosition != ListView.INVALID_POSITION) { View oldSelected = getListView().getChildAt(mPreviousPosition); oldSelected.setBackgroundResource(R.drawable.menu_button); ((ImageView) oldSelected.findViewById(R.id.selector_icon)).setImageDrawable(icons.getDrawable(mPreviousPosition)); ((TextView) oldSelected.findViewById(R.id.selector_text)).setTextAppearance(getActivity(), R.style.text_selector); } //Select this item View newSelected = getListView().getChildAt(position); newSelected.setBackgroundResource(R.drawable.menu_button_active); ((ImageView) newSelected.findViewById(R.id.selector_icon)).setImageDrawable(icons_active.getDrawable(position)); ((TextView) newSelected.findViewById(R.id.selector_text)).setTextAppearance(getActivity(), R.style.text_selector_active); mPreviousPosition = position; } </code></pre> <p>When I call this after an item has been selected, it works great. But when I try highlight the first item on startup, I get a NPE at </p> <pre><code>newSelected.setBackgroundResource(R.drawable.menu_button_active); </code></pre> <p>It seems <code>getListView().getChildAt(position)</code> is returning <code>null</code> because the Fragment's view hasn't been created yet.</p> <p>So, from where in my Activity is it safe to try initialise the <code>ListFragment</code>? I've tried in onStart, onRestoreInstanceState and onResume but they all produce the NPE.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload