I'm converting an existing app to the Fragments API using the compatibility library. I've read that you're supposed to update classes that extend Activity to now use FragmentActivity. This is fine for most cases, but what about classes that extend ListActivity or MapActivity? What is the preferred way to handle this? I was hoping there was a ListFragmentActivity or something along those lines, but I don't see one.
There is a ListFragment: http://developer.android.com/reference/android/app/ListFragment.html
For MapActivity, unfortunately you will need to continue to use that; there is no Fragment API for it.
This is what I do when converting a ListActivity to the fragments API:
Replace
lv = getListView();withlv = (ListView) findViewById(android.R.id.list);Replace
setListAdapter(adapter);withlv.setAdapter(adapter);If you have overriden
onListItemClick(), replace it withlv.setOnItemClickListener(new ListView.OnItemClickListener() {...You'll have to set the empty view (that shows when there are no results) manually:
lv.setEmptyView(findViewById(android.R.id.empty));If I'm using CursorLoader, I normally put this in onLoadFinished():
// if there are no results if (data.getCount() == 0) { // let the user know lv.setEmptyView(findViewById(android.R.id.empty)); } else { // otherwise clear it, so it won't flash in between cursor loads lv.setEmptyView(null); }Speaking of cursor loaders, I'll also convert the activity to use CursorLoader if it isn't already by that point
At least for the ListActivity You can change it to FragmentActivity (Still implementing OnItemCLickListener) and replace:
lv=getListView() to lv=(ListView) findViewById(R.id.your_list_view_id)
and
setListAdapter(favAdapter) to lv.setAdapter(adapter)
It is possible to convert the ListActivity to a FragmentActivity.
- Extend
FragmentActivityinstead ofListActivity - Create
res/layout/your_activity.xmlwith an emptyListViewwithandroid:id="@+id/your_activity_list_view" - In the
onCreateof your activity,setContentView(R.layout.your_activity); - Also change the
onCreateof your activity to explicitly retrieve theListViewyou just inflated
.
ListView lv = (ListView) findViewById(R.id.your_activity_list_view);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
来源:https://stackoverflow.com/questions/6497121/what-to-do-about-listactivity-mapactivity-when-converting-to-fragments-using-the