FragmentPagerAdapter with ViewPager and two Fragments. Go to the first from the second and update first's text

前端 未结 3 739
Happy的楠姐
Happy的楠姐 2021-02-06 07:29

I\'m not familiar with FragmentPagerAdapter, so this is going to be one of those questions that we (you) read the description critically.

Structure:

3条回答
  •  感情败类
    2021-02-06 07:43

    Disclaimer: Although this had worked perfectly fine for me before, you should be aware of the classic pitfalls of depending on internal, private behavior. While I wrote tests that would eventually warn me if the internal implementation changed, I have since moved on to greener pastures. And you should, too. As such, the value of this question and its answer is only historical, in my opinion.


    Sorry about that question, I think it was the hour.

    To solve that problem, I implemented this solution as is. Seems to work just fine. So, I believe it was just a matter of finding the (currently attached) fragment instance by figuring out how its Id is named. The link above explains how it's made.

    I opted to answer my own question instead of deleting it because I believe novices like me on these pagers will benefit from a "real case scenario". Most of the answers I've seen talk most about the theory, which is the right way BTW... but without a real example to work on sometimes people like me get lost.

    Anyway, here is the last piece of code that I needed (the commented part above):

    int n = 0;
    mViewPager.setCurrentItem(n); // in the question I had stopped here.
    
    ExcerptsFragment f = (ExcerptsFragment) ContainerActivity.this
            .getSupportFragmentManager().findFragmentByTag(getFragmentTag(n));
    f.triggerRefresh();
    
    // ... below the helper method: used the solution from the link.
    
    private String getFragmentTag(int pos){
        return "android:switcher:"+R.id.pager+":"+pos;
    }
    

    So, I'm having a feeling that this is a robust solution, because I'm not holding any references to fragments (thus risking the references being outdated). I kept my own code at a minimum, therefore minimizing the chances of me doing something stupid.

    Of course, if you have something to add, to show us, to tell what is wrong in doing it or what can be improved, I'll be glad to hear from you.

提交回复
热议问题