【问题标题】:How to get FragmentManager from Application context?如何从应用程序上下文中获取 FragmentManager?
【发布时间】:2017-10-19 00:43:00
【问题描述】:

我有一个 LinearLayout,将 BottomSheetDialogFragment 称为 in this example

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?

编辑匕首 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();
    }
}

以及对应的接口:

public interface IApplicationComponent {
    Application getApplication();
}

【问题讨论】:

  • 您不应该从视图中调用 BottomSheetDialogFragment 或任何其他片段;片段可以包含视图,但视图不能包含片段。尝试从活动或其他片段中显示您的 BottomSheetDialogFragment。祝你好运!

标签: android android-fragments android-context fragmentmanager


【解决方案1】:

添加为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();

【讨论】:

  • 是Dagger注入的,我只有Application context可以调用DemoUIView(Application context)
  • 你可以再试一次。@RalfWickum
  • 你的意思是什么?!
  • 使用获取FragmentManager的方式。
  • 是的,告诉我。应用程序不交付它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-31
  • 2020-04-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多