如何从 FragmentActivity 获取片段实例? [英] How to get the fragment instance from the FragmentActivity?

查看:24
本文介绍了如何从 FragmentActivity 获取片段实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在FragmentActivity中设置了content view,activity会根据布局文件中指定的类名为我创建fragment实例.但是我怎样才能得到那个片段实例?

I set the content view in the FragmentActivity, and the activity will create the fragment instance for me according to the class name specified in the layout file. But how can I get that fragment instance?

public class MyActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle extra) {
        super.onCreate(extra);
        setContentView(R.layout.page_fragment);
    }
}

布局/page_fragment.xml:

layout/page_fragment.xml:

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/pageview"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:name="org.xi.android.PageFragment" />

推荐答案

你可以在FragmentManager中使用findFragmentById.

由于您正在使用支持库(您正在扩展 FragmentActivity),您可以使用:

Since you are using the Support library (you are extending FragmentActivity) you can use:

getSupportFragmentManager().findFragmentById(R.id.pageview)

如果您没有使用支持库(因此您使用的是 Honeycomb+ 并且不想使用支持库):

If you are not using the support library (so you are on Honeycomb+ and you don't want to use the support library):

getFragmentManager().findFragmentById(R.id.pageview)

请注意,即使在 Honeycomb+ 上也建议使用支持库.

Please consider that using the support library is recommended even on Honeycomb+.

这篇关于如何从 FragmentActivity 获取片段实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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