Android - Set fragment id

前端 未结 7 1577
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 15:22

How can I set a Fragment\'s Id so that I can use getSupportFragmentManager().findFragmentById(R.id.--)?

相关标签:
7条回答
  • 2020-11-27 16:20

    Turns out you may not need to know the fragment id.

    From the docs:

    public abstract Fragment findFragmentById (int id)
    
    Finds a fragment that was identified by the given id either
    when inflated from XML or as the container ID when added in
    a transaction.
    

    The important part is "as the container ID when added in a transaction".

    so:

    getSupportFragmentManager()
        .beginTransaction()
        .add(R.id.fragment_holder, new AwesomeFragment())
        .commit();
    

    and then

    AwesomeFragment awesome = (AwesomeFragment)
         getSupportFragmentManager()
              .findFragmentById(R.id.fragment_holder);
    

    will get you whatever (awesome) fragment is held in R.id.fragment_holder.

    0 讨论(0)
提交回复
热议问题