将 SupportActionBar 与 androidx FragmentActivity 结合使用
Use SupportActionBar with androidx FragmentActivity
我想在我的 Android 应用程序中使用 Material 设计组件。该应用程序已经使用 androidx 向后兼容以前版本的 Android,使用 SDK 28.
编译
我的应用程序中的所有活动都从 BaseActivity
class 扩展,后者又扩展了 androidx.fragment.app.FragmentActivity
(例如,我在屏幕上有一个相机片段)。
但是,当我将应用程序的主题更改为 Material 设计主题时,例如
<style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar" />
然后 MenuInflater 不再工作:
getMenuInflater().inflate(R.menu.activity_options, menu);
我在尝试加载操作栏时收到 NullPointerException (getActionBar()
returns null
):
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
...
}
我在网上其他地方看到有人使用 AppCompatActivity.getSupportActionBar()
的例子,但这对我没有用,因为 androidx.fragment.app.FragmentActivity
没有扩展 AppCompatActivity
。
有没有一种方法可以在不需要重新设计整个应用程序的情况下正确地实现Material设计?
应用的摘录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.
您的 BaseActivity
可以扩展 AppCompatActivity
而不是 FragmentActivity
因为 androidx.appcompat.app.AppCompatActivity
扩展 androidx.fragment.app.FragmentActivity
.
这样就可以使用方法AppCompatActivity.getSupportActionBar()
.
我想在我的 Android 应用程序中使用 Material 设计组件。该应用程序已经使用 androidx 向后兼容以前版本的 Android,使用 SDK 28.
编译我的应用程序中的所有活动都从 BaseActivity
class 扩展,后者又扩展了 androidx.fragment.app.FragmentActivity
(例如,我在屏幕上有一个相机片段)。
但是,当我将应用程序的主题更改为 Material 设计主题时,例如
<style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar" />
然后 MenuInflater 不再工作:
getMenuInflater().inflate(R.menu.activity_options, menu);
我在尝试加载操作栏时收到 NullPointerException (getActionBar()
returns null
):
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
...
}
我在网上其他地方看到有人使用 AppCompatActivity.getSupportActionBar()
的例子,但这对我没有用,因为 androidx.fragment.app.FragmentActivity
没有扩展 AppCompatActivity
。
有没有一种方法可以在不需要重新设计整个应用程序的情况下正确地实现Material设计?
应用的摘录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.
您的 BaseActivity
可以扩展 AppCompatActivity
而不是 FragmentActivity
因为 androidx.appcompat.app.AppCompatActivity
扩展 androidx.fragment.app.FragmentActivity
.
这样就可以使用方法AppCompatActivity.getSupportActionBar()
.