gpt4 book ai didi

android - 判断 Parent 是 Activity 还是 FragmentActivity

转载 作者:行者123 更新时间:2023-11-29 17:55:09 25 4
gpt4 key购买 nike

我有一个自定义小部件保存为 android 库项目。
自定义小部件使用 fragment ,因此需要访问应用程序的 fragment 管理器。

我希望我的自定义小部件与扩展 Activity(Honeycomb 或更高版本)的应用程序以及扩展 FragmentActivity 的应用程序兼容。

为了实现这一点,我需要我的自定义小部件根据父级是否扩展 Activity 或 FragmentActivity 来决定是使用 getFragmentManager() 还是 getSupportFragmentManager() ,如下所示。

switch (getApplicationType()) {
case ACTIVITY__HONEYCOMB_ONWARD
FragmentManager fm = ((Activity)getContext()).getFragmentManager();
//...
break;
case FRAGMENT_ACTIVITY
FragmentManager fm = ((FragmentActivity)getContext()).getSupportFragmentManager();
//...
break;
//...

让我感到困惑的一点是如何在我的 getApplicationType() 方法中编写测试。

private int getApplicationType() {
if (??? How do I write this test ???) {
return ACTIVITY__HONEYCOMB_ONWARD;
} else if (??? How do I write this test ???) {
return FRAGMENT_ACTIVITY;
} else {
//...
}
}

最佳答案

使用instanceof

例如:

if ( getParent() instanceof Activity ) {
return ACTIVITY;
} else if ( getParent() instanceof Fragment ) {
return FRAGMENT;
} etc…

关于android - 判断 Parent 是 Activity 还是 FragmentActivity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19920226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com