将SupportActionBar与androidx FragmentActivity一起使用

时间:2019-10-09 09:15:52

标签: android android-actionbar android-support-library android-appcompat androidx

我想在我的Android应用程序中使用Material Design组件。该应用程序已经使用androidx来向后兼容早期版本的Android,并使用SDK 28进行了编译。

应用程序中的所有活动都从androidx.fragment.app.FragmentActivity类扩展,而该类又扩展了<style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar" /> (例如,我在屏幕上有一个摄像头片段)。

但是,当我将应用程序的主题更改为“材料设计”主题时,例如

getMenuInflater().inflate(R.menu.activity_options, menu);

然后MenuInflater不再起作用:

getActionBar()

,尝试加载操作栏时,我得到了NullPointerException(null返回@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActionBar().setDisplayHomeAsUpEnabled(true); ... } ):

AppCompatActivity.getSupportActionBar()

我看到了一些在网上其他地方使用androidx.fragment.app.FragmentActivity的人的例子,但这对我没有用,因为AppCompatActivity不扩展build.gradle

是否有一种方法可以正确实施Material Design,而无需重新设计整个应用程序?

应用程序的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" } 的提取:

{{1}}

1 个答案:

答案 0 :(得分:3)

  

但这对我没有用,因为androidx.fragment.app.FragmentActivity不会扩展AppCompatActivity。

由于BaseActivity扩展了AppCompatActivity,因此您的FragmentActivity可以扩展androidx.appcompat.app.AppCompatActivity而不是androidx.fragment.app.FragmentActivity

通过这种方式,您可以使用方法AppCompatActivity.getSupportActionBar()