Android - How do I manage multiple instances of a single fragment with different content?

后端 未结 1 1472
你的背包
你的背包 2021-01-05 16:02

I want to be able to setText and getText of Views of individual Fragments. As it is now, when I setText of a Framgent\'s TextView it changes the text of that View in all Fra

相关标签:
1条回答
  • 2021-01-05 16:45

    Fragments are added to stack with a parameter named tag. In your case you've added your fragment with "testtag".

    fragmentTransaction.add(R.id.test_fragment, fragment, "testtag");
    

    If you create multiple instances of same fragment and add them with unique tags, then you are able to get them with that unique tags. When you get a fragment then you can reach its content.

    FragmentManager fm = this.getSupportFragmentManager();
    Fragment testtagFragment = fm.findFragmentByTag("testtag"); 
    View targetView = testtagFragment.getView().findViewById(R.id.anyViewInsideContentOfYourFragment);
    

    Edit:

    I want to be able to setText and getText of Views of individual Fragments.

    This question has 2 parts.

    1. To setText while initializing you have to pass your initial parameters to your fragment while creating its instance. I suggest you to use a static newInstance method for this. See sample here
    2. To getText read my answer above. Note that, you can get the content of a fragment after its onCreateView method is executed. So If you try to call getView method of a fragment at your activities onCreate method (after you add the fragment), that will return null. You can get its content successfully under a click event to test that, and use get or set operations of any view on that fragment's content.
    0 讨论(0)
提交回复
热议问题