【问题标题】:Access view from Fragment A in Fragment B从 Fragment B 中的 Fragment A 访问视图
【发布时间】:2014-12-21 20:53:18
【问题描述】:

我试图从片段 B 中的片段 A 访问 Textview 以更改文本,我得到一个空指针。我试过以下。

public void setText(String text) { TextView t = (TextView) getView().findViewById(R.id.message_menu); t.setText(text); }

我也试过了

 test = (TextView) getView().findViewById(R.id.message_menu);
 test.setText("bla bla");

我也尝试过夸大另一个视图

View myFragmentView = inflater.inflate(R.layout.fragment_login, container, false);
test = (TextView) test..findViewById(R.id.message_menu);

尝试在 Fragment B 中使用带有以下代码的 NewInstance

test = (TextView) FragmentLogin.newInstance().getView().findViewById(R.id.TEXT_STATUS_ID);
test.setText("hello testing ");

和片段 A:

 public static FragmentBottomMenu newInstance() {
    FragmentBottomMenu fragment = new FragmentBottomMenu();
    return fragment;
}

仍然得到一个空指针异常。

任何建议都会很棒。谢谢

【问题讨论】:

  • 不要这样做,这是不好的做法。通知活动导致文本更改的任何事件,并让活动在第二个片段上调用一些公共方法。

标签: android android-fragments views


【解决方案1】:

您的代码示例指向 current 片段的视图!要正确访问其他 Fragment 的视图,请使用以下命令:

text = (TextView) [otherFragmentInstance].getView().findViewById(R.id.message_menu);
text.setText("bla bla");

【讨论】:

  • 您好,感谢您的回答,我尝试了您的解决方案,但仍然出现空异常。我已经更新了我的问题,它显示了我尝试过的代码.. 谢谢
猜你喜欢
  • 1970-01-01
  • 2021-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多