Android Set Text of TextView in Fragment that is in FragmentPagerAdapter

前端 未结 4 1694

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:29

    The TextView is located in the fragments layout, not in the ViewPagers or the PagerAdapter, that is causing the NPE. Now, you have 2 options.

    • The first is the easiest, you should simple move your code for changing the text into the corresponding fragment's class, FragmentA in this case.
    • Secondly, you could make the TextView into FragmentA static, so it can be accessed by other classes. So your code would look something like this:

       ....
       TextView myText;
      
       @Override
       public View onCreateView(....) {
      
           myLayout = ....;
      
           myText = myLayout.findViewById(yourID);
      
           ....
      }
      

    And then you would change the text from somewhere else (if it's really necessary):

       FragmentA.myText.setText("new text");
    

    Explaining method 2

    Use the following in your Fragment.

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

    Then change the text like:

    FragmentA.setText("Lulz");
    

提交回复
热议问题