Mar*_*rco 3 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);
}
}
Run Code Online (Sandbox Code Playgroud)
}
活动的相应布局:
<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>
Run Code Online (Sandbox Code Playgroud)
现在,我不明白为什么内部类InfoFragment中的onCreateView()中的ViewGroup容器是一个nullpointer,我也不明白,为什么
ViewGroup infoFragmentRoot = (ViewGroup) getActivity().findViewById(
R.id.infoFragmentRoot) ;
Run Code Online (Sandbox Code Playgroud)
返回也为null.
感谢您的反馈.
你在这里遇到了一些问题.首先,您不希望在标记内添加<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;
Run Code Online (Sandbox Code Playgroud)
请注意,inflate()的attach参数是false?Android将负责稍后将返回的视图附加到您的容器.
在片段获得onActivityCreated()回调之前,不保证您的活动的视图层次结构存在.因此,获取infoFragmentRoot的尝试可能会在onCreateView()内返回null.但是我甚至不确定当标签被埋在你的内部时会发生什么<fragment>.
在这种特殊情况下,您将标记嵌入到活动的布局中,将使用标记中的其余属性调用片段的onInflate()回调.理论上,您可以将这些属性添加到片段上的参数包中,然后在onCreateView()中使用setArguments()和getArguments())检索这些值.我在理论上说,因为看起来代码中存在处理配置更改的错误(例如,横向到纵向),导致在配置更改后重建片段时onCreateView()之后调用onInflate().请参阅缺陷报告http://code.google.com/p/android/issues/detail?id=14796.
现在,我建议您将片段的布局提取到单独的布局XML文件(例如,frag1.xml),使用上面的代码在onCreateView()中扩展该布局.并且不要担心传递给onInflate()的任何属性.
| 归档时间: |
|
| 查看次数: |
5442 次 |
| 最近记录: |