I want to use Material Design components in my Android application. The app already uses androidx for backwards compatibility with previous versions of Android, compiling with SDK 28.
All of the activities in my application extend from a BaseActivity
class, which in turn extends androidx.fragment.app.FragmentActivity
(I have a camera fragment on the screen, for example).
However, when I change the theme of my application to a Material Design theme, e.g.
<style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar" />
then the MenuInflater no longer works:
getMenuInflater().inflate(R.menu.activity_options, menu);
and I get a NullPointerException when trying to load the action bar (getActionBar()
returns null
):
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
...
}
I have seen examples of people using AppCompatActivity.getSupportActionBar()
elsewhere online, but this is not useful to me as androidx.fragment.app.FragmentActivity
does not extend AppCompatActivity
.
Is there a way to implement Material Design properly without needing to rearchitect the entire application?
Extract of the app's build.gradle
:
android {
buildToolsVersion "29.0.0"
compileSdkVersion 28
defaultConfig {
minSdkVersion 19
targetSdkVersion 23
}
}
dependencies {
implementation "androidx.core:core:1.1.0"
implementation "com.google.android.material:material:1.1.0-beta01"
}
but this is not useful to me as androidx.fragment.app.FragmentActivity does not extend AppCompatActivity.
Your BaseActivity
can extend AppCompatActivity
instead of FragmentActivity
since the androidx.appcompat.app.AppCompatActivity
extends androidx.fragment.app.FragmentActivity
.
In this way you can use the method AppCompatActivity.getSupportActionBar()
.