【问题标题】:Use SupportActionBar with androidx FragmentActivity将 SupportActionBar 与 androidx FragmentActivity 一起使用
【发布时间】:2019-10-09 09:15:52
【问题描述】:

我想在我的 Android 应用程序中使用 Material Design 组件。该应用已使用 androidx 向后兼容以前版本的 Android,使用 SDK 28 编译。

我的应用程序中的所有活动都扩展自 BaseActivity 类,而后者又扩展了 androidx.fragment.app.FragmentActivity(例如,我在屏幕上有一个相机片段)。

但是,当我将应用程序的主题更改为 Material Design 主题时,例如

<style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar" />

然后 MenuInflater 不再工作:

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

我在尝试加载操作栏时收到 NullPointerException(getActionBar() 返回null):

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  getActionBar().setDisplayHomeAsUpEnabled(true);
  ...
}

我在网上其他地方看到有人使用AppCompatActivity.getSupportActionBar() 的例子,但这对我没有用,因为androidx.fragment.app.FragmentActivity 没有扩展AppCompatActivity

有没有一种方法可以在不需要重新架构整个应用程序的情况下正确实现 Material Design?

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

【问题讨论】:

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


    【解决方案1】:

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

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

    这样就可以使用AppCompatActivity.getSupportActionBar()的方法了。

    【讨论】:

    • 谢谢!我刚刚在这里看到了有关 Android 支持库的另一个问题的答案:stackoverflow.com/a/19118936/9988519
    • @Fraser 是的,ActionBarActivity 是由 AppCompatActivity 多年前弃用的支持库提供的旧类。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    相关资源
    最近更新 更多