java – Combining ListActivity and ActionBarActivity-ThrowExceptions

Exception or error:

I am currently building for a minimum SDK of 10, so I have to use the android-support-v7-appcompat library to implement ActionBar. I have setup the ActionBar, but I want to now add a ListActivity, however this requires extending my class and Java doesn’t have multiple inheritance. What should I do?

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu items for use in the action bar
    MenuInflater inflater = getMenuInflater();
    getSupportActionBar().setIcon(R.drawable.ic_action_search);
    getSupportActionBar().setDisplayShowHomeEnabled(false);
    getSupportActionBar().setDisplayShowTitleEnabled(false);
    inflater.inflate(R.menu.main_activity_actions, menu);
    return super.onCreateOptionsMenu(menu);
   }

 }
How to solve:

ListActivity hasn’t been ported to AppCompat. Probably because you should consider it ‘deprecated’, and instead use a ListFragment.

Fragments will work with a ActionBarActivity, just make sure they are fragments from the support library.

Have a read through this link about fragments.

For your use case, I would just define the fragment in xml.

###

The easiest way to do this is to use a ListFragment inside of the ActionBarActivity. I did it like this:

public class MyActivity extends ActionBarActivity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        MyFragment fragment = new MyFragment();
        getSupportFragmentManager().beginTransaction().replace(android.R.id.content, fragment).commit();
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home: {
                finish();
                break;
            }

            default: {
                break;
            }
        }
        return true;
    }

    public static class MyFragment extends ListFragment {

        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            ...
        }

        public void onListItemClick(ListView listView, View view, int position, long id) {
            ...
        }
    }
}

This way you don’t even need an xml for it, and it works well.

Leave a Reply

Your email address will not be published. Required fields are marked *