不要在片段中获取rootLayoutContainer(Android 3.0预览版)

时间:2011-02-14 12:41:27

标签: android android-fragments android-3.0-honeycomb

我目前正在进入Android 3.0预览版的片段API,并构建了以下最小编码:

我有一个Activty,它将嵌入Fragment(s),目前实现如下:

public class Cockpit extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.cockpit);
}

public static class InfoFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        ViewGroup infoFragmentRoot = (ViewGroup) getActivity().findViewById(
                R.id.infoFragmentRoot) ;

        return inflater.inflate(R.id.infoFragment, container, false);
    }
}

}

活动的相应布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<fragment android:name="test.android.ui.cockpit.Cockpit$InfoFragment"
        android:id="@+id/infoFragment"
        android:layout_weight="1"
        android:layout_width="10dp"
        android:layout_height="match_parent" >
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" 
                 android:layout_height="match_parent" android:padding="12dp" android:id="@+id/infoFragmentRoot" >
        <TextView  
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
            android:text="@string/hello"
        />
    </LinearLayout>
</fragment>

现在,我不明白为什么内部类InfoFragment中的onCreateView()中的ViewGroup容器是一个nullpointer,我也不明白, 为什么

ViewGroup infoFragmentRoot = (ViewGroup) getActivity().findViewById(
                R.id.infoFragmentRoot) ;

也返回null。

感谢您的反馈。

2 个答案:

答案 0 :(得分:8)

你在这里遇到了一些问题。首先,您不希望在<fragment>标记内添加标记。将fragment标记视为占位符。片段的onCreateView()方法负责定义片段的视图层次结构,而不是活动的布局XML文件。你可以做的是创建一个单独的布局XML文件,使其只是片段的布局。然后在onCreateView()中,你接受传入的inflater,并做这样的事情:

    View v = inflater.inflate(R.layout.frag1, container, false);
    TextView text1 = (TextView) v.findViewById(R.id.text1);
    text1.setText( myTextData );
    return v;

请注意,inflate()的attach参数是false? Android会在稍后将返回的视图附加到您的容器中。

在片段获得onActivityCreated()回调之前,不保证您的活动的视图层次结构存在。因此,获取infoFragmentRoot的尝试可能会在onCreateView()内返回null。但是我甚至不确定当这个标签埋在你的<fragment>内时会发生什么。

在这种特殊情况下,您将标记嵌入到活动的布局中,将使用标记中的其余属性调用片段的onInflate()回调。理论上,您可以将这些属性添加到片段上的参数包中,然后在onCreateView()中使用setArguments()和getArguments())检索这些值。我在理论上说,因为它看起来在代码中有一个错误处理配置更改(例如,横向到纵向),导致onInflate()在 onCreateView()之后被称为,当重建片段时配置更改后。请参阅缺陷报告http://code.google.com/p/android/issues/detail?id=14796

现在,我建议您将片段的布局提取到单独的布局XML文件(例如,frag1.xml),使用上面的代码在onCreateView()中扩充该布局。并且不要担心传递给onInflate()的任何属性。

答案 1 :(得分:0)

您也不想使用onCreate来实例化您的布局,所有内容都将在父活动中处理。保存捆绑包是迄今为止我们在那里完成的所有工作