【发布时间】:2019-10-04 19:35:15
【问题描述】:
我正在尝试将setOnClickListener 写入另一个位于我的主要活动中名为InsertFragment 的fragment 内的按钮
我是 android 开发的新手,所以我不明白为什么会出现这个错误。我曾尝试使用setContentView(R.layout.fragment_insert),但没有成功
当我从菜单栏中选择相关片段时,我的片段将被调用
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
这是我得到的错误。请纠正我的错误。提前致谢
【问题讨论】:
-
你不能从你的活动中调用你的片段视图。并让我们知道您为什么尝试从活动中访问片段按钮?
-
请提供代码
-
@RajasekaranM 因为我的菜单栏在主要活动中。我也不能在片段类中使用 findViewByid(R.id.my_id) 方法。这就是我尝试这种方式的原因
-
使用回调与您的活动进行通信
-
@SauravKumar case R.id.nav_insert: getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new InsertFragment()).commit();执行插入帧();休息;
标签: android android-fragments layout android-button main-activity