如何使用类名而不是索引实例化片段类 [英] How to instantiate fragment class using class name instead of index
问题描述
我有两个名为 SessionTab
和 BillingTab
的片段类,而我正尝试使用
I have two fragment class named SessionTab
and BillingTab
and i am trying to create instance of those class using
SessionTab sessionTab = (SessionTab) getSupportFragmentManager().getFragments().get(1);
,但是有时这些类的索引被颠倒,然后导致 ClassCastException
but sometimes index for those classes are reversed and then it causes ClassCastException
我该如何通过传递类名而不是索引来获取那些片段类的实例,或者如何确保这些类的索引每次都保持不变,从而不会导致 ClassCastException
>
How can i get instance of those fragment class by passing class name instead of index or any way to make sure that index of those class stays the same everytime so it doesn't cause ClassCastException
推荐答案
使用以下方法之一: findFragmentById()
和 findFragmentByTag()
方法.
Use one of this methods : findFragmentById()
and findFragmentByTag()
methods.
参考文献: https://developer.android.com/reference/android/app/FragmentManager.html#findFragmentById(int)
更新:
ClassCastException
.在您的情况下,您的 FragmentManager
返回的片段与 SessionTab
不同,因此将引发异常.
ClassCastException
is invoked when you are not casting the appropriate classes to one another. In your case, Your FragmentManager
is returning different fragment than SessionTab
, so the exception is thrown.
如果使用 findFragmentById()
或 findFragmentByTag()
,则它将完全返回您想要的片段,并且不会引发异常.
If you use findFragmentById()
or findFragmentByTag()
, then it will return the fragment exactly what you want, and exception will not be thrown.
这篇关于如何使用类名而不是索引实例化片段类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!