【问题标题】:i can't find fragment by tag我无法按标签找到片段
【发布时间】:2015-04-20 23:14:38
【问题描述】:

我正在尝试查找我通过标签创建的片段

tachoFrag = (menu1_Fragment) getFragmentManager().findFragmentByTag("Tacho");

overviewFrag= (menu2_Fragment)getFragmentManager().findFragmentByTag("Overview");

dataLogFrag = (menu3_Fragment) getFragmentManager().findFragmentByTag("Datalogger");

transaction = getFragmentManager().beginTransaction();

但是当我尝试替换框架的内容时,我遇到了一个空问题,因为找不到片段......帮助?

【问题讨论】:

  • 你也应该发布更多代码和你的 logcat。
  • log cat : 'java.lang.NullPointerException: 尝试在空对象引用上调用虚拟方法 'void app.z0nen.slidemenu.menu3_Fragment.setData(double, int, int, double)' app.z0nen.slidemenu。 MyActivity$2.handleMessage (MyActivity.java:270)'
  • ' if (tachoFrag != null && tachoFrag.isVisible()) { tachoFrag.setRevs(revs); tachoFrag.setSpeed(速度); tachoFrag.setFuelGauge(燃料); } transaction.replace(R.id.container, tachoFrag);事务.commit(); } '

标签: android android-fragments


【解决方案1】:

试试下面的代码

MyFragment fragment= (MyFragment)getFragmentManager().findFragmentByTag("FRAGMENT_TAG");
if(null != fragment  && fragment.isVisible()){
    //execute your codes here

}

【讨论】:

  • 欢迎来到 Stack Overflow!尽管此答案可能是正确且有用的,但如果您随附一些解释以解释它如何帮助解决问题,则最好。如果有更改(可能不相关)导致它停止工作并且用户需要了解它曾经是如何工作的,这在未来变得特别有用。
  • ' 事务 = getFragmentManager().beginTransaction(); transaction.replace(R.id.container, new menu1_Fragment(),"Tacho");事务.commit(); tachoFrag = (menu1_Fragment) getFragmentManager().findFragmentByTag("Tacho");'但 logcat 一直向我显示此错误尝试在空对象引用上调用虚拟方法 'void app.z0nen.slidemenu.menu1_Fragment.setRevs(int)'
【解决方案2】:

在您的代码 transaction.replace(R.id.container, tachoFrag); 中,您没有提供 TAG。

应该是transaction.replace(R.id.container, tachoFrag, "TAG");

这样你就可以使用getFragmentManager().findFragmentByTag("TAG")

【讨论】:

  • 好像也有问题。您正在检查tachoFrag.isVisible() 并调用一些方法,然后在同一个片段上调用replace。为什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多