Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListFragment how to get the listView?

Tags:

java

android

I'm porting my app from AsyncTasks to Fragements.

But how can I access the listView (id: list) element within my fragment?

class MyFragment extends ListFragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.list_fragment, container, false);
        ListView listView = getListView(); //EX: 
        listView.setTextFilterEnabled(true);
        registerForContextMenu(listView);
        return v;
    }
}

xml:

        <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ListView>

Ex:

Caused by: java.lang.IllegalStateException: Content view not yet created
like image 994
membersound Avatar asked May 19 '12 11:05

membersound


4 Answers

as the onCreateView doc stays:

creates and returns the view hierarchy associated with the fragment

so since the method does not return, you will are not able to access the ListView through getListView(). You can obtain a valid reference in the onActivityCreated callback. Or you can try using v.findViewById(android.R.id.list) if the ListView is declared inside list_fragment.xml

like image 191
Blackbelt Avatar answered Sep 29 '22 13:09

Blackbelt


get list View from the view, you are getting earlier.

View view = inflater.inflate(android.R.layout.list_content, null);
    ListView ls = (ListView) view.findViewById(android.R.id.list);
    // do whatever you want to with list.
like image 42
Pratap Singh Avatar answered Sep 29 '22 15:09

Pratap Singh


The easiest and more reliable solution to this problem will be to override onActivityCreated(); and do your list manipulations there.

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    ListView listView = getListView(); //EX: 
    listView.setTextFilterEnabled(true);
    registerForContextMenu(listView);
    super.onActivityCreated(savedInstanceState);
}
like image 41
C-- Avatar answered Sep 29 '22 13:09

C--


I was able to access the ListView by the OnViewCreated method instead.

like image 26
TombMedia Avatar answered Sep 29 '22 14:09

TombMedia