How to set a Tag to a Fragment in Android

痴心易碎 提交于 2020-01-13 07:59:09

问题


I've looked at all the questions on Stackoverflow but could not find a single definitive answer to this question. How do you set a Tag to a Fragment so that you can retrieve it via getFragmentManager().findFragmentByTag()? Could someone give a simple code example of how to create a tag to a Fragment?


回答1:


You can set a Tag during fragment transaction.

For example if it's a replace transaction you could do it like so:

FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
        .replace(R.id.fragment_container, mFragment, TAG)
        .commit();

If the Fragment you're using is not from Support Library, use getFragmentManager() instead of getSupportFragmentManager().




回答2:


I used that feature to provide between Dialog box and Fragment. When a alteration is made in Dialogbox, App can easily update Fragment UI

MyFragment.

DialogFragment dialog = LastCycleDate.newInstance( last_period_start );
        dialog.setTargetFragment( this, 0 );
        dialog.show( getActivity().getSupportFragmentManager(), "showLastCycleDate" );

MyDailogBox.java

Fragment targetFragment; = getTargetFragment();
if( targetFragment instanceof IntroParentFragment ){
            IntroParentFragment introParentFragment = ( IntroParentFragment ) targetFragment;
            introParentFragment.mutualMethods.setLastCycleStartDay( start_date );
        }


来源:https://stackoverflow.com/questions/30062129/how-to-set-a-tag-to-a-fragment-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!