当然,您可以在片段中编写任何代码,但您需要注意一些事情。在访问需要上下文的任何内容或特定于活动的内容时,您将需要获取对片段的超级活动的引用,例如在活动中创建意图时,您可以执行以下操作:
Intent intent = new Intent(this,SomeActivity.class);
但在片段内你将不得不做这样的事情:
Intent intent = new Intent(super.getActivity(),SomeActivity.class);
同样,如果您正在从片段的布局文件访问某些内容。您需要执行以下步骤:
1)在片段内获取对片段父布局的全局引用。例如
private LinearLayout result_view;
2)实现OnCreateView方法而不是onCreate方法。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return result_view;
}
3)在片段的 onCreateView 方法中像这样膨胀片段布局:
result_view = (LinearLayout) inflater.inflate(
R.layout.image_detail_pager, container, false);
4)您现在可以像这样访问布局视图:
layout_a = (LinearLayout) result_view
.findViewById(R.id.some_layout_id);