Android AppCompatActivity

January 4, 2018 Oclemy Android Activity 1 minute, 48 seconds

AppCompatActivity is a class that acts as the super class for activities that want to take advantage of the support library action bar features.

The requirement to use the android.support.v7.app.ActionBar inside you activity are:

  1. To be running API level 7 or higher.
  2. Then extend this class.
  3. Set you activity theme to android.support.v7.appcompat.R.style#Theme_AppCompat Theme.AppCompat or similar theme.

Themes do get set in the androidmanifest.xml e.g

<activity
      android:name=".MainActivity"
      android:label="@string/app_name"
      android:theme="@style/AppTheme.NoActionBar">....</activity>

AppCompatActivity is defined inside the android.support.v7.app package:

package android.support.v7.app;

It derives from android.support.v4.app.FragmentActivity:

public class AppCompatActivity extends FragmentActivity{}

And implements several interfaces:

public class AppCompatActivity extends FragmentActivity implements AppCompatCallback,TaskStackBuilder.SupportParentable, ActionBarDrawerToggle.DelegateProvider {}

Setting AppCompatActivity theme

AppCompatActivity like other activity themes can be set either via androidmanifest

<activity
      android:name=".MainActivity"
      android:label="@string/app_name"
      android:theme="@style/AppTheme.NoActionBar">....</activity>

or programmatically via the setTheme() method:

public void setTheme(@StyleRes final int resid) {}

Retrieving AppCompatActivity ActionBar

AppCompatActivity gives us a method to retrieve a reference to its action bar:

public ActionBar getSupportActionBar(){}

If it doesn't have one then null gets returned.

Using ToolBar as an ActionBar in AppCompatActivity

We can use android.support.v7.widget.Toolbar instead of an actionbar. Toolbars have the advantage of flexibility in use and customizations.

ActionBars are normally part of the Activity's opaque window decor. Hence they are controlled by the framework.

ToolBars on the other hand can be used within your application's layout. Hence they are flexible.

Say that we have a toolbar defined as follows:

...
<android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />
...

inside our activity_main.xml.

We can use it as action bar using the setSupportActionBar() where we pass the toolbar reference as a parameter.

public void setSupportActionBar(@Nullable Toolbar toolbar) {}

Example:

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

To clear it you pass null.

Comments