Access view from Fragment A in Fragment B

2019-02-28 02:24发布

Im trying to access a Textview from Fragment A in Fragment B to change the text, im getting a null pointer. ive tried the following.

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

i have also tried

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

I have tried inflating another view too

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

Tried using a NewInstance with the following code in Fragment B

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

And Fragment A :

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

still getting a null pointer exception.

Any suggestions would be great. Thanks

1条回答
Rolldiameter
2楼-- · 2019-02-28 03:01

Your code examples are pointing to the View of the current Fragment! To properly access the other Fragment's View, use this:

text = (TextView) [otherFragmentInstance].getView().findViewById(R.id.message_menu);
text.setText("bla bla");
查看更多
登录 后发表回答