Android Set Text of TextView in Fragment that is in FragmentPagerAdapter

前端 未结 4 1766

This one is driving me nuts. Basically, I want to create a ViewPager and add a few Fragments to it. Then, all I want to do, it set a value in one of th

4条回答
  •  没有蜡笔的小新
    2021-02-04 15:23

    This line:

    TextView t = (TextView) findViewById(R.id.someTextViewInFragmentA);
    

    is looking for the view in your ParentActivity. Of course it wont find it and that's when you get your NPE.

    Try something like this:

    1. Add a "tag" to your fragments when you add them

    2. Use someFragment = getSupportFragmentManager().findFragmentByTag("your_fragment_tag")

    3. Get the view of the fragment fragmentView = someFragment.getView();

    4. And finally find your TextView and set the text

      TextView t = (TextView) fragmentView.findViewById(R.id.someTextViewInFragmentA); t.setText("some text");

提交回复
热议问题