这是一个家庭作业,我遇到了一些困难,我正在尝试创建一个将由我的所有 Activity 扩展的 BaseActivity。我想制作一个方法,直接在 BaseActivity 中配置和显示我的 fragment ,所以在 Activity 中我只需要传递 2 个参数( fragment fragment ,int 框架布局)
public void configureAndShowFragment(BaseFragment fragment, int layout) {
fragment = (BaseFragment) getSupportFragmentManager().findFragmentById(layout);
if (fragment == null && findViewById(layout) != null) {
fragment = new fragment // <== init fragment here
getSupportFragmentManager().beginTransaction()
.add(layout, fragment)
.commit();
}
}
我在遇到一些困难时添加了评论,“在这里初始化 fragment ”我的目标是能够用正确的类型初始化我的 fragment ,例如“new Mainfragment,new DetailsFragment”我的问题是我想对我的参数 fragment 做一些测试,这样我就可以知道我的参数 fragment 的类型是什么,这样我就可以用正确的类型初始化它。
最佳答案
您可以这样做,首先使用反射获取 fragment 类型,如果您无法通过 ID 找到它,则创建它。
public void configureAndShowFragment(BaseFragment fragment, int layout) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
if (fragment == null) {
throw new RuntimeException("fragment cannot be null");
}
String fragmentClassName = fragment.getClass().getName();
fragment = (BaseFragment) getSupportFragmentManager().findFragmentById(layout);
if (fragment == null && findViewById(layout) != null) {
Class<?> clazz = Class.forName(fragmentClassName);
Constructor<?> ctor = clazz.getConstructor();
fragment = (BaseFragment) ctor.newInstance(); <== init fragment here
getSupportFragmentManager().beginTransaction()
.add(layout, fragment)
.commit();
}
}
尽管被转换为 BaseFragment
,但如果您执行 fragment.getClass().getName()
,您将拥有 fragment 最初具有的子类型。
关于java - 查找在参数方法中传递的对象的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57885766/