FragmentManager从上下文 [英] FragmentManager from Context

查看:138
本文介绍了FragmentManager从上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个新的查看类。在这一类我需要访问 FragmentManager ,但我无法弄清楚如何。

我可以访问 FragmentManager 从上下文?

  CustomView扩展的LinearLayout
 

解决方案

只有在特定环境下延伸活动(后蜂窝)或FragmentActivity(pre-蜂窝)。

在这种情况下,你就必须做出100%肯定它使用反射或尝试副渔获物的活动。

 尝试{
  最后活动活动=(活动)范围内;

  //返回片段经理
  返回activity.getFragmentManager();

  //如果使用的是支持库。
  //返回activity.getSupportFragmentManager();

}赶上(ClassCastException异常E){
  Log.d(TAG,无法获取该片段经理这种);
}
 

我以为我建议重构所以查看实际上只是意味着展示的东西,不应该实际修改您的应用程序的状态,但是这是我的看法。

I created a new View class. Within that class I need to get access to the FragmentManager, but I cannot figure out how.

Can I access the FragmentManager from a context?

CustomView extends LinearLayout

解决方案

Only if the given Context extends Activity (Post-Honeycomb) or FragmentActivity (pre-honeycomb).

In which case you'd have to make 100% sure it's an activity using reflection or try-catch.

try{
  final Activity activity = (Activity) context;

  // Return the fragment manager
  return activity.getFragmentManager();

  // If using the Support lib.
  // return activity.getSupportFragmentManager(); 

} catch (ClassCastException e) {
  Log.d(TAG, "Can't get the fragment manager with this");
}

Thought I recommend refactoring so a View is really just meant for showing stuff and shouldn't actually modify the state of your app, but that's my opinion.

这篇关于FragmentManager从上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆