Search code examples
androidandroid-actionbar-compat

ActionBarActivity of "android-support-v7-appcompat" and ListActivity in Same activity


How to use ActionBarActivity of "android-support-v7-appcompat" in the activity which Extends the ListActivity.

For Example I have an Activity

public class xxxxxListActivity
  extends ListActivity implements OnItemSelectedListener  { 
  // ...................
} 

In the above activity i want to use "ActionBarActivity" but as java dosent support multiple inheritance I am not able to get it working.


Solution

  • Here's an implementation of ActionBarListActivity:

    public abstract class ActionBarListActivity extends ActionBarActivity {
    
    private ListView mListView;
    
    protected ListView getListView() {
        if (mListView == null) {
            mListView = (ListView) findViewById(android.R.id.list);
        }
        return mListView;
    }
    
    protected void setListAdapter(ListAdapter adapter) {
        getListView().setAdapter(adapter);
    }
    
    protected ListAdapter getListAdapter() {
        ListAdapter adapter = getListView().getAdapter();
        if (adapter instanceof HeaderViewListAdapter) {
            return ((HeaderViewListAdapter)adapter).getWrappedAdapter();
        } else {
            return adapter;
        }
    }
    }
    

    Just like regular ListActivity, you'll need a layout that contains a ListView with the ID android.R.id.list ("@android:id/list" in XML).

    The spiel in getListAdapter() is to handle cases where header views have been added to the ListView. Seems like ListView sets its own adapter to a HeaderViewListAdapter, so we have to try and get the wrapped adapter to prevent casting errors.

    Edit: Try adding this function to satisfy the need for onListItemClick:

    protected void onListItemClick(ListView lv, View v, int position, long id) {
        getListView().getOnItemClickListener().onItemClick(lv, v, position, id);
    }