Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add ActionBar to an activity which already extends ListActivity?

I have an Activity which extends ListActivity.
Can I add an ActionBar without extending ActionBarActivity?

like image 508
Mridul S Kumar Avatar asked Apr 23 '15 08:04

Mridul S Kumar


2 Answers

You can use the new AppCompatDelegate component provided by the Support Library.

ActionBar is now deprecated and you should use a Toolbar, to be compliant with Material Design. You can use the Toolbar provided by the support library.

Add it to your xml layout like this:

<android.support.v7.widget.Toolbar

        android:id="@+id/my_awesome_toolbar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:minHeight="56dp"
        android:background="?attr/colorPrimary"

        />

Be sure to use a NoActionBar theme in your styles.xml. Use the Material Design color tags.

<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
</style>

Then, add the AppCompatDelegate to your Activity, in OnCreate(), like this.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    AppCompatCallback callback = new AppCompatCallback() {
        @Override
        public void onSupportActionModeStarted(ActionMode actionMode) {
        }

        @Override
        public void onSupportActionModeFinished(ActionMode actionMode) {
        }
    };

    AppCompatDelegate delegate = AppCompatDelegate.create(this,callback);

    delegate.onCreate(savedInstanceState);
    delegate.setContentView(R.layout.activity_main);

    Toolbar toolbar= (Toolbar) findViewById(R.id.my_awesome_toolbar);
    delegate.setSupportActionBar(toolbar);


}

Note: To create an AppCompatDelegate you need to pass the Activity itself and a callback, good practice should be implementing the callback in your Activity, but for shortening reasons I created an instance in onCreate().

like image 113
Mariux Avatar answered Oct 23 '22 03:10

Mariux


Use holo themes in styles.xml Because you can use ActionBar only after holo

Use this :

<style name="AppTheme" parent="android:Theme.Holo">
like image 22
N Kaushik Avatar answered Oct 23 '22 04:10

N Kaushik