How to set a Fragment tag by code?

前端 未结 8 2383
我寻月下人不归
我寻月下人不归 2020-12-01 02:26

I haven\'t found something like setTag(String tagName) method in the Fragment class. The only way to set a Fragment tag that I have fo

8条回答
  •  隐瞒了意图╮
    2020-12-01 02:50

    This is the best way I have found :

       public class MainActivity extends AppCompatActivity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (savedInstanceState == null) {
              // Let's first dynamically add a fragment into a frame container
              getSupportFragmentManager().beginTransaction(). 
                  replace(R.id.flContainer, new DemoFragment(), "SOMETAG").
                  commit();
              // Now later we can lookup the fragment by tag
              DemoFragment fragmentDemo = (DemoFragment) 
                  getSupportFragmentManager().findFragmentByTag("SOMETAG");
            }
        }
    }
    

提交回复
热议问题