创建多个片段的通用方法

时间:2016-03-03 17:30:37

标签: java android generics android-fragments

我想写一个为我创建多个片段的方法,我不知道该怎么做。经过几次尝试后,我感到更加困惑。

这是我通常如何创建两个片段

private void createFragDog(Animals animals) {
    DogFragment frag = DogFragment.newInstance(ArrayList<Dogs> animals.getDogs());
    ...    
    *frag.(do fragment manager stuff and commit())*
    ...
}

第二次调用创建片段

private void createFragCat(Animals animals) {
    CatFragment frag = CatFragment.newInstance(ArrayList<Cats> animals.getCats());
    ...    
    *frag.(do fragment manager stuff and commit())*
    ...
}

由于newInstance方法是静态的,我似乎无法弄清楚如何制作泛型方法并只传入类类型。传递给newInstance的对象也不总是一个数组。这是我的尝试:

private <T,E> void animalFragments(Class<T> frag, Class<E> animalType, Object obj){
    if (obj == null) return;
    if (obj instanceof List<?>) {
        if (((List<E>)obj).isEmpty()) return;
    }

    try {
        T fragment = (T) frag.newInstance();
        ?? Not sure what to do now or how to call up method that is static but specific to both.

    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:0)

以此方式希望对您有所帮助。

private <T,E> void animalFragments(Class<T> frag, Object obj){
    Method m = null;
    try {
        m = frag.newInstance().getClass().getDeclaredMethod("newInstance", obj.getClass());
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

    if (m != null) {
        T fragment = null;
        try {
            fragment = (T) m.invoke(null, obj);

            if (fragment != null) {
                FragmentTransaction trans = this.getSupportFragmentManager().beginTransaction();
                trans.add(R.id.ll_fragments_container, (Fragment) fragment, fragment.getClass().getSimpleName());
                trans.commit();
                return true;
            }
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }
}