如何从Application上下文获取FragmentManager?

时间:2017-10-19 00:43:00

标签: android android-fragments android-context fragmentmanager

我有一个LinearLayout,将BottomSheetDialogFragment称为Link2

static class DemoUIView extends LinearLayout {

  DateView dateView;

  public DemoUIView(Context context){ // Constructor
    //..
    dateView.setOnClickListener(v-> {
      BottomSheetDialogFragment bottomSheetDialogFragment = new BottomSheet3DialogFragment();
      bottomSheetDialogFragment.show(getFragmentManager(), bottomSheetDialogFragment.getTag());
    })
  }
}

但我无法访问FragmentManager那里.. 如何从那里调用BottomSheetDialogFragment?

EDIT Dagger 2.11:

public class DemoApplication extends Application implements HasActivityInjector {

    @Inject
    DispatchingAndroidInjector<Activity> activityInjector;

    @Override
    public void onCreate() {
        super.onCreate();
        DemoApplicationComponent appComponent = DaggerDemoApplicationComponent.builder()
                .application(this)
                .build()
    }

    @Override
    public AndroidInjector<Activity> activityInjector() {
        return activityInjector;
    }

}

和DemoApplicationComponent:

@ApplicationScope
@Component(
        modules = {
                ApplicationModule.class
        }
)
public interface DemoApplicationComponent extends IApplicationComponent {
    @Component.Builder
    interface Builder {
        @BindsInstance
        Builder application(Application application);
        DemoApplicationComponent build();
    }
}

和相应的interfaec:

public interface IApplicationComponent {
    Application getApplication();
}

1 个答案:

答案 0 :(得分:0)

将其添加为Constructor参数

private DateView dateView;
private FragmentManager mFragmentManager;

public DemoUIView(Context context, FragmentManager mFragmentManager) { // Constructor
    //..
    this.mFragmentManager = mFragmentManager;
    dateView.setOnClickListener(v -> {
        BottomSheetDialogFragment bottomSheetDialogFragment = new BottomSheet3DialogFragment();
        bottomSheetDialogFragment.show(getFragmentManager(), bottomSheetDialogFragment.getTag());
    })
}

修改

// use android.app.FragmentManager
FragmentManager fragmentManager = ((Activity)context).getFragmentManager();
// android.support.v4.app.FragmentManager
FragmentManager fragmentManager = ((FragmentActivity)context).getSupportFragmentManager();