AndroidX 导航抽屉

dia*_*viu 2 java android android-studio navigation-drawer androidx

在搜索和搜索之后,我无法向 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" />
Run Code Online (Sandbox Code Playgroud)

我已将导航视图更改为底部导航视图。

    //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 {
Run Code Online (Sandbox Code Playgroud)

但我不明白它的工作。现在出现其他错误,

错误:

找不到符号方法 setNavigationItemSelectedListener(MainPageActivity) bottomNavView.setNavigationItemSelectedListener(this); ^ 符号:方法 setNavigationItemSelectedListener(MainPageActivity) 找不到符号方法 getHeaderView(int) View headerView = bottomNavView.getHeaderView(0); ^ 符号:方法 getHeaderView(int)

我该如何解决所有这些错误?

Sum*_*kla 6

您应该使用headerlayoutfornavigation drawer而不是 BottomNavigation

AndroidX是对原来的一个重大改进,Android Support Library. 使项目使用androidX。

  • Refactor-> Migrate to androidX.

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

在您的 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>
Run Code Online (Sandbox Code Playgroud)

在你的java文件中:

 navigationView.setNavigationItemSelectedListener(YourClass.this);
Run Code Online (Sandbox Code Playgroud)

内部应用级主题:

<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>
Run Code Online (Sandbox Code Playgroud)