【问题标题】:nullpointerexception when calling fragment methods from activity从活动调用片段方法时出现空指针异常
【发布时间】:2013-01-16 02:37:36
【问题描述】:

我有一个片段活动,它通过以下方式调用其他片段:

FragmentView1 f = (FragmentView1) this.getSupportFragmentManager()
                .findFragmentByTag(getFragmentTag(0));

而我的 getFragmentTag() 函数是:

private String getFragmentTag(int pos){
    return "android:switcher:"+R.id.viewpager+":"+pos;   //fragmentpageradapter auto generated tag
}

不是问题是每当我调用 f.somemethod 时,我都会得到一个空指针异常。

我试过了

Log.w("HELLO1",""+ f.getTag());

它返回 nullpointerexception 。

【问题讨论】:

  • 我猜你的 getFragmentTag(0) 没有返回你所期望的
  • 不,它返回了正确的标签。我在 FragmentView1 中调用了“getTag()”,在 FragmentActivity 中调用了“getFragmentTag(0)”,两者都返回了相同的结果

标签: android nullpointerexception fragment


【解决方案1】:

findFragmentByTag() 返回 null,因为它没有根据 docs 找到具有指定标记的片段。确保您在布局中或在事务时以编程方式设置片段的标签。

有关更多信息,请参阅this 问题。

【讨论】:

  • 我正在使用 fragmentpageradapter,它会自动为片段生成标签,我正在使用 getFragmentTag,它会检索片段的自动生成标签
猜你喜欢
  • 2013-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-12
相关资源
最近更新 更多