如何从不同的片段中获取某物的 ID:Android

How to get the ID of something from a different fragment: Android

我正在使用片段和 bottomnavigationview 构建应用程序。我的一个片段中有一个按钮,当按下它时,它会转到另一个片段。但是当fragment改变的时候,bottomNavigationView选中的item没有改变。

所以我希望能够从第一个片段中获取 navigationView 的 id,然后在单击按钮时更改 selectedItem。

点击按钮的代码如下:

button1.setOnClickListener(new View.OnClickListener(){
            public void onClick(View view) {
                searchTerm = "Colorful";
                HomeFragment fragment = new HomeFragment();
                FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.content, fragment, "");
                fragmentTransaction.commit();
                Log.e("Home item", String.valueOf(R.id.nav_home));
                Log.e("BottomNavigationView id", String.valueOf(navigationView));
                //navigationView.setSelectedItemId(R.id.nav_home);
            }
        });

bottomNavigationView id 正在返回 null。所以我只需要能够从这个片段中得到它的ID,然后使用注释掉的代码行来切换选择的导航项。

在我的 onCreate 中我有 navigationView = view.findViewById(R.id.navigation);

您可以使用以下代码在您的样式中使用样式来更改所选项目 class,

 // bottom theme
<style name="Theme.App" parent="Theme.MaterialComponents">
    //style the color, size and other features of bottom navigation bar
    <item name="bottomNavigationStyle">style="@style/Widget.MaterialComponents.BottomNavigationView.Colored</item>
    <item name="colorPrimary">@color/purple_700</item>
    <item name="colorOnPrimary">@color/teal_700</item>
    <item name="actionMenuTextColor">@color/white</item>
</style>

然后在 xml 文件中的 BottomNavigationView 中使用此样式

android:theme="@style/Theme.App"

我建议你使用Material BottomNavigationView,它易于使用并且有更多的功能可以设计。您可以从 here.

获取完整代码