How do I get the currently displayed fragment?

前端 未结 30 2199
青春惊慌失措
青春惊慌失措 2020-11-22 11:21

I am playing with fragments in Android.

I know I can change a fragment by using the following code:

FragmentManager fragMgr = getSupportFragmentManag         


        
30条回答
  •  借酒劲吻你
    2020-11-22 11:40

    Here is a Kotlin solution:

    if ( this.getSupportFragmentManager().getBackStackEntryCount()>0 ) {
        var fgmt = this.getSupportFragmentManager().fragments[this.getSupportFragmentManager().getBackStackEntryCount()-1]
        if( fgmt is FgmtClassName ) {
            (fgmt as FgmtClassName).doSth()
        }
    }
    

    Simplified way:

    with ( this.getSupportFragmentManager() ) {
        if ( getBackStackEntryCount()>0 ) {
            var fgmt = fragments[getBackStackEntryCount()-1]
            if ( fgmt is FgmtClassName ) {
                (fgmt as FgmtClassName).doSth()
            }
        }
    }
    

提交回复
热议问题