フレデリック・Wojcikowski:
これは宿題であると私はすべての私の活動によって拡張されるBaseActivityを作成しようとしている、いくつかの困難を抱えています。私は活動の内部で、私はちょうど2つのparamsを渡す必要があります設定とBaseActivityに直接私の断片を表示するメソッドをしたいと思います(フラグメントフラグメント、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();
}
}
私はここに私の目標は正しいタイプで私のフラグメントを初期化することができるようにすることです「initはここ断片」と、私はいくつかの困難を抱えているコメントを追加しました、例えば、「新Mainfragmentは、新しいDetailsFragment」ここに私の問題は、私がしたいということです私は正しいタイプでそれを初期化することができますので、私は私のparamフラグメントの種類が何であるかを知ってもらうことができますので、私のparamフラグメントにいくつかのテストを行います。
アリ・ベンZarrouk:
あなたは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()
あなたは、フラグメントが最初に持っていたことをサブタイプを持つことになります。