What to do about ListActivity/MapActivity when converting to Fragments using the compatibility library?

谁说胖子不能爱 提交于 2019-11-29 05:47:10

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:

  1. Replace lv = getListView(); with lv = (ListView) findViewById(android.R.id.list);

  2. Replace setListAdapter(adapter); with lv.setAdapter(adapter);

  3. If you have overriden onListItemClick(), replace it with lv.setOnItemClickListener(new ListView.OnItemClickListener() {...

  4. 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);
    }
    
  5. 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)

Ellesmera

It is possible to convert the ListActivity to a FragmentActivity.

  1. Extend FragmentActivity instead of ListActivity
  2. Create res/layout/your_activity.xml with an empty ListView with android:id="@+id/your_activity_list_view"
  3. In the onCreate of your activity, setContentView(R.layout.your_activity);
  4. Also change the onCreate of your activity to explicitly retrieve the ListView you just inflated

.

ListView lv = (ListView) findViewById(R.id.your_activity_list_view);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!