Search code examples
androidandroid-fragmentsfragmentstatepageradapterpagerslidingtabstrip

SetText not working when Changing tabs


I have a SlidingTabLayout and I'm attempting to change a settext every time a different page (Fragment) is selected.

I am attempting to do this through the fragments themselves. I have 3 total, and i'm doing so by calling getActivity() in the onCreateView

The application does not crash, but this causes the tabs to display the incorrect tab name on each tab. They are out of order and can display the name twice depending on the order clicked.

I'm not sure what I am doing wrong. Here's my current code:

Tab 1-3:

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    TextView textView = (TextView)getActivity().findViewById(R.id.pageName);
    textView.setText("Tab X");

    return inflater.inflate(R.layout.discover_fragment,container,false);

}

I can display more code if requested. All help is appreciated.


Solution

  • Open your SlidingTabLayout.java, and add this line at the beginning of the class:

    private ArrayList<TextView> mTextView = new ArrayList<>();
    

    Add this line below something like tabTitleView.setText(adapter.getPageTitle(i));:

    mTextView.add(tabTitleView);
    

    Finally, add this method:

    public void changeTitle(int position) {
        final PagerAdapter adapter = mViewPager.getAdapter();
        TextView tv = mTextView.get(position);
        if (tv != null) {
            tv.setText(adapter.getPageTitle(position));
        }
    }
    

    Now you can call changeTitle(0) to change the title text for tab 0.