【问题标题】:How to call a fragment-class from inside another fragment in android如何从android中的另一个片段内部调用片段类
【发布时间】:2013-04-09 18:21:30
【问题描述】:

在我的项目中,我有一个片段视图(as the layout of a sliding menu),它附加到我的 MainActivity。在我的菜单片段中,我有另一个片段 (内部片段),它从 XML 本身调用一个类,如下所示:

<fragment
    android:id="@+id/innerfragment"
    android:layout_width="fill_parent"
    android:layout_height="175dip"
    android:layout_marginBottom="10dip"
    android:layout_marginTop="10dip"
    class="com.myproject.android.fragment.MyInnerFragment" />

当我运行项目时,它显示以下java.lang.RuntimeException

 android.view.InflateException: Binary XML file line #76: Error inflating class fragment

问:如何从 XML 或代码调用内部片段类?

同样的XML 在引入滑动菜单之前设置在活动下时正在工作。

EDIT:

为了清楚起见,这就是布局的样子。滑动菜单视图是一个名为 menu.xml 的 RelativeLayout

内部片段内容根据在 MainActivity 中选择的选项而有所不同。

【问题讨论】:

  • class="com.myproject.android.fragment$MyInnerFragment" $ 为内部类签名
  • @Selvin 我试过这段代码。但我得到了android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.utm.android.fragment$MyInnerFragment: make sure class name exists, is public, and has an empty constructor that is public。该类是公共的,并且还有一个空的构造函数。 :( +1 尝试.. :)
  • 内部类是静态的吗?如果不是,那么这可能是问题...(是的,如果您将内部类更改为静态,则无法访问外部类而不引用它)
  • 没有。每次在扩展滑动菜单的活动中进行更改时,内部片段内容都会发生变化。我添加了一张图片以使其更清晰。
  • 你见过NestedFragment Sample吗...??

标签: android android-fragments android-fragmentactivity


【解决方案1】:

我想我已经找到了我的问题的解决方案。

首先,我为我的项目(Maven 项目) 使用了错误的 android 支持 jar。 ;)

我用latest android support jar 文件解决了这个问题,第二个问题可能是我的内部片段在创建外部视图之前就已经设置好了。

无论如何,我将这段代码插入到我的外部片段中,它开始工作一切正常..!

@AfterInject
public void setupfragment()
{
      FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
      myinnerFragment = new PresetsFragment_();
      fragmentTransaction.add( R.id.menu_my_frame, myinnerFragment );
      fragmentTransaction.commit();
}

总是欢迎更好的答案。在那之前,我将此答案标记为正确答案..! ;)

编辑:

忘了提到我从 XML 中删除了我的代码,并从我的外部片段内的代码中实现了它。 :D

【讨论】:

  • @SalmanKhan 谢谢,但我想知道是否有更好的答案..! ;)
猜你喜欢
  • 2021-06-13
  • 1970-01-01
  • 1970-01-01
  • 2017-06-09
  • 2015-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多