简体   繁体   English

如何从应用程序上下文中获取FragmentManager?

[英]How to get FragmentManager from Application context?

I have a LinearLayout, to call a BottomSheetDialogFragment as in this example 我有一个LinearLayout,如本例中那样调用BottomSheetDialogFragment

static class DemoUIView extends LinearLayout {

  DateView dateView;

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

But I can not access the FragmentManager there.. How can I call the BottomSheetDialogFragment from there? 但是我不能在那里访问FragmentManager。 如何从那里调用BottomSheetDialogFragment?

EDIT Dagger 2.11 : 编辑匕首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;
    }

}

and DemoApplicationComponent: 和DemoApplicationComponent:

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

and the corresponding interfaec: 以及相应的接口:

public interface IApplicationComponent {
    Application getApplication();
}

Add it as Constructor parameter 将其添加为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());
    })
}

Edit 编辑

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM