AndroidX 导航抽屉

AndroidX Navigation Drawer

找了又找,还是没能完全迈出AndroidX的一步。我有导航抽屉的问题。

<android.support.design.internal.BottomNavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main_page"
    app:menu="@menu/activity_main_page_drawer" />

我已将 navigationView 更改为 bottomNavigationView。

    //NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    BottomNavigationView bottomNavView = (BottomNavigationView) findViewById(R.id.nav_view);
    bottomNavView.setNavigationItemSelectedListener(this);
    View headerView = bottomNavView.getHeaderView(0);
    TextView navUsername = (TextView) headerView.findViewById(R.id.textnav);
    navUsername.setText(str);


public class MainPageActivity extends AppCompatActivity
    implements BottomNavigationView.OnNavigationItemSelectedListener {

但我无法正常工作。现在出现其他错误,

错误:

cannot find symbol method setNavigationItemSelectedListener(MainPageActivity) bottomNavView.setNavigationItemSelectedListener(this); ^ symbol: method setNavigationItemSelectedListener(MainPageActivity) cannot find symbol method getHeaderView(int) View headerView = bottomNavView.getHeaderView(0); ^ symbol: method getHeaderView(int)

如何解决所有这些错误?

您应该为 navigation drawer 使用 headerlayout 而不是 BottomNavigation

AndroidX是对原来的Android Support Library.的重大改进 所以要使项目使用 androidX.

  • 转到 Refactor-> Migrate to androidX.

  • buid.gradle

  • 添加 implementation com.google.android.material.material:1.1.0-alpha09

在你的xml中:

<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_home"
        app:menu="@menu/menu_home_drawer" />

</androidx.drawerlayout.widget.DrawerLayout>

在您的 java 文件中:

 navigationView.setNavigationItemSelectedListener(YourClass.this);

内部应用级主题:

<style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>