【问题标题】:invoke a button click event from main activity when the button is inside another fragment当按钮位于另一个片段内时,从主活动调用按钮单击事件
【发布时间】:2019-10-04 19:35:15
【问题描述】:

我正在尝试将setOnClickListener 写入另一个位于我的主要活动中名为InsertFragmentfragment 内的按钮

我是 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


【解决方案1】:

确保您的 Button 已声明并已初始化

类似的东西

Button addButton = findViewById(R.id.add_button);

【讨论】:

  • 这意味着您在按钮类的空引用上调用 OnClickListener
  • 我能够通过在我的片段中初始化那些视图(按钮,编辑文本)来解决这个问题。然后我尝试通过意图将这些数据传递给我的主要活动。但我仍然得到一个空异常
  • public void sendData() { Intent i = new Intent(getActivity().getBaseContext(),MainActivity.class); //打包数据 i.putExtra("SENDER_KEY", "InsertFragment"); i.putExtra("NAME_KEY", name.getText().toString()); i.putExtra("DESCRIPTION_KEY",description.getText().toString()); i.putExtra("PRICE_KEY", Float.valueOf(price.getText().toString())); //重置小部件 name.setText("");描述.setText("");价格.setText(""); //开始活动 getActivity().startActivity(i); }
猜你喜欢
  • 1970-01-01
  • 2014-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多