获取片段动态附着到<&的FrameLayout GT ;? [英] Get Fragment dynamically attached to <FrameLayout>?

查看:212
本文介绍了获取片段动态附着到<&的FrameLayout GT ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗯,我有一个简单的<的FrameLayout>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/FragmentContainer"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

然后在我的code,我添加了一个片段是:

Then in my code, i added a Fragment to it:

FragClass aFrag = new FragClass();
getSupportFragmentManager().beginTransaction()
        .replace(R.id.FragmentContainer, aFrag).commit();

和其他地方在我的code,我想要得到的 FragClass(延伸片段)从ID R.id 对象。 FragmentContainer

And somewhere else in my code, i want to get that FragClass (extends Fragment) object from the ID R.id.FragmentContainer.

我已经尝试过

((ViewGroup) findViewById(R.id.FragmentContainer)).getChildAt(0)

((FrameLayout) findViewById(R.id.FragmentContainer)).getChildAt(0)

但他们返回查看,而不是片段连接到它。

but they are returning the View, instead of the Fragment attached to it.

我知道我能保持变量 aFrag 的地方,所以我并不需要再次找到它。但我认为应该有一种方法来retieve吧。

i know i can keep the variable aFrag somewhere, so i do not need to find it again. But i believe there should be a way to retieve it.

推荐答案

让我把它包起来通过一个完整的答案:)

Let me wrap it up by a full answer :)

在这种情况下,动态添加片段使用容器的ID 查看的ViewGroup )。

In this case, the dynamically added Fragment uses the ID of the container View (ViewGroup).

REF:<一href="http://developer.android.com/guide/components/fragments.html#Adding">http://developer.android.com/guide/components/fragments.html#Adding

请注意:每个片段都需要一个唯一的标识符,该系统可以用它来恢复片段,如果该活动将重新启动(并且你可以用它来捕捉片段进行交易,如将其删除)。有三种方式来提供一个片段一个ID:

Note: Each fragment requires a unique identifier that the system can use to restore the fragment if the activity is restarted (and which you can use to capture the fragment to perform transactions, such as remove it). There are three ways to provide an ID for a fragment:

      
  • 供应机器人:一个唯一的ID id属性
  •   
  • 供应机器人:用一个唯一的字符串标记属性
  •   
  • 如果你没有提供的previous二,本系统采用容器视图的ID。
  •   
  • Supply the android:id attribute with a unique ID.
  • Supply the android:tag attribute with a unique string.
  • If you provide neither of the previous two, the system uses the ID of the container view.

这是因为它是一个片段毕竟,我们必须使用 getSupportFragmentManager()。findFragmentById()来检索它,它返回一个 Fragent ,而不是 findViewById()返回一个查看

It is because it is a Fragment afterall, we have to use getSupportFragmentManager().findFragmentById() to retrieve it, which returns a Fragent, instead of findViewById() which returns a View.

所以,回答这个问题的办法是:

So the answer to this problem would be:

((aFrag) getSupportFragmentManager().findFragmentById(R.id.FragmentContainer))

感谢@Luksprog。

这篇关于获取片段动态附着到&lt;&的FrameLayout GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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