Java 另一个片段中的引用按钮

Java 另一个片段中的引用按钮,java,android,fragment,bottomnavigationview,Java,Android,Fragment,Bottomnavigationview,这可能真的很简单,但我想不出来。我在Android Studio中创建了一个底部导航活动。我在第三个标签上有一个按钮。当应用程序启动时,将打开第一个选项卡。我想引用这个按钮,这样当用户点击那个标签,然后点击那个按钮时,我可以做一些事情 这只是自动启动活动 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.a

这可能真的很简单,但我想不出来。我在Android Studio中创建了一个底部导航活动。我在第三个标签上有一个按钮。当应用程序启动时,将打开第一个选项卡。我想引用这个按钮,这样当用户点击那个标签,然后点击那个按钮时,我可以做一些事情

这只是自动启动活动

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    BottomNavigationView navView = findViewById(R.id.nav_view);
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
            R.id.navigation_test, R.id.navigation_list, R.id.navigation_add)
            .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
    NavigationUI.setupWithNavController(navView, navController);

    // I tried to reference the button here

}

我尝试了
Button add\u Button=findviewbyd(R.id.add\u add\u Button),但返回null。可能是因为我没有参加那个活动。我怎样才能参照这个按钮?在
onCreate
或其他地方这样做好吗?

您必须研究布局结构,以便了解哪个视图是按钮的父视图。找到父视图后,可以在父视图本身上调用findViewById。你必须先把它引用到变量中。我不确定我是否理解。。。该片段称为
R.layout.fragment\u notifications
如何将片段放入变量中,例如,如果我调用变量buttonView,是否可以转到
Button Button=buttonView.findViewById(R.id.Button)
假设您从模板创建了一个项目,您可以打开与第三个选项卡对应的布局文件,并为按钮分配一个id,然后编辑相应的活动。您必须使用rootView上的findViewById引用带有R.id.myButton的按钮。