Fragment 类
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
片段是应用程序的用户界面或行为中的一部分,可以放置在其中 Activity。
[Android.Runtime.Register("android/app/Fragment", DoNotGenerateAcw=true)]
public class Fragment : Java.Lang.Object, Android.Content.IComponentCallbacks2, Android.Views.View.IOnCreateContextMenuListener, IDisposable
[<Android.Runtime.Register("android/app/Fragment", DoNotGenerateAcw=true)>]
type Fragment = class
inherit Object
interface IComponentCallbacks2
interface IComponentCallbacks
interface IJavaObject
interface IDisposable
interface IJavaPeerable
interface View.IOnCreateContextMenuListener
- 继承
- 派生
- 特性
- 实现
注解
此类在 API 级别 28 中已弃用。 使用 Jetpack 片段库androidx.fragment.app.Fragment 在所有设备和 访问生命周期时保持一致的行为。
片段是应用程序的用户界面或行为中的一部分,可以放置在活动中。 片段通过活动或片段通过其FragmentManager或FragmentManager属性公开的一个FragmentManager管理。 在 Android 6.0 及更高版本中,其他对象可以通过托管片段 FragmentHostCallback。 片段有自己的生命周期,具体取决于它的主机。 活动停止时,其片段无法保持启动状态。 当活动被销毁时,保留的片段实例可以在其娱乐中幸存下来。 要使框架重新创建片段,片段类必须具有公共无参数构造函数。 如果该构造函数不可用,状态还原可能会失败并出现运行时异常。
有关使用片段的详细信息,请阅读 片段 开发人员指南。
片段的生命周期包括附件、创建、视图和用户交互的回调。 在 Android 6.0 及更高版本上, OnAttach(Context) 将片段与其主机相关联。 在 Android 5.0 和 5.1 上,回调为 OnAttach(Activity)。 OnCreate(Bundle) 执行初始创建,并 OnCreateView(LayoutInflater, ViewGroup, Bundle) 可以创建其视图层次结构。 OnActivityCreated(Bundle) 遵循活动的创建; OnViewStateRestored(Bundle) 在视图存在时,遵循视图状态的还原。 OnStart() 启动片段,并 OnResume() 启动用户交互。
当片段不再使用时, OnPause() 并 OnStop() 停止其交互和生命周期。
OnDestroyView() 允许它清理视图资源, OnDestroy() 执行最终清理,并在 OnDetach() 删除其主机关联之前。 保留的实例不会收到另一个OnCreateOnDestroy或活动娱乐期间。
片段可用作应用程序布局的一部分,以组织界面并将其适应屏幕。 以下示例显示项列表和每个项的详细信息。
活动的布局 XML 可以包括 <片段> 标记,用于在布局中嵌入片段实例。 例如,下面是嵌入一个片段的简单布局:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment"
android:id="@+id/titles"
android:layout_width="match_parent" android:layout_height="match_parent" />
</FrameLayout>
布局以正常方式安装在活动中:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_layout);
}
标题片段(显示标题列表)相当简单,它的大部分工作都依赖于 ListFragment。 请注意单击某个项的实现:根据当前活动的布局,它可以创建并显示一个新片段以显示就地的详细信息(稍后更详细),或启动一个新活动以显示详细信息。 此示例改编自 Android 示例。
public static class TitlesFragment extends ListFragment {
boolean mDualPane;
int mCurCheckPosition = 0;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Populate list with our static array of titles.
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES));
// Check to see if we have a frame in which to embed the details
// fragment directly in the containing UI.
View detailsFrame = getActivity().findViewById(R.id.details);
mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
if (savedInstanceState != null) {
// Restore last state for checked position.
mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
}
if (mDualPane) {
// In dual-pane mode, the list view highlights the selected item.
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// Make sure our UI is in the correct state.
showDetails(mCurCheckPosition);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
showDetails(position);
}
/**
* Helper function to show the details of a selected item, either by
* displaying a fragment in-place in the current UI, or starting a
* whole new activity in which it is displayed.
*/
void showDetails(int index) {
mCurCheckPosition = index;
if (mDualPane) {
// We can display everything in-place with fragments, so update
// the list to highlight the selected item and show the data.
getListView().setItemChecked(index, true);
// Check what fragment is currently shown, replace if needed.
DetailsFragment details = (DetailsFragment)
getFragmentManager().findFragmentById(R.id.details);
if (details == null || details.getShownIndex() != index) {
// Make new fragment to show this selection.
details = DetailsFragment.newInstance(index);
// Execute a transaction, replacing any existing fragment
// with this one inside the frame.
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.details, details);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
} else {
// Otherwise we need to launch a new activity to display
// the dialog fragment with selected text.
Intent intent = new Intent();
intent.setClass(getActivity(), DetailsActivity.class);
intent.putExtra("index", index);
startActivity(intent);
}
}
}
显示所选项内容的详细信息片段仅基于内置于应用的字符串数组的索引显示文本字符串:
public static class DetailsFragment extends Fragment {
/**
* Create a new instance of DetailsFragment, initialized to
* show the text at 'index'.
*/
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
// We have different layouts, and in one of them this
// fragment's containing frame doesn't exist. The fragment
// may still be created from its saved state, but there is
// no reason to try to create its view hierarchy because it
// won't be displayed. Note this is not needed -- we could
// just run the code below, where we would create and return
// the view hierarchy; it would just never be used.
return null;
}
ScrollView scroller = new ScrollView(getActivity());
TextView text = new TextView(getActivity());
int padding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
4, getActivity().getResources().getDisplayMetrics());
text.setPadding(padding, padding, padding, padding);
scroller.addView(text);
text.setText(Shakespeare.DIALOGUE[getShownIndex()]);
return scroller;
}
}
在这种情况下,当用户单击标题时,当前活动中没有详细信息容器,因此游戏片段的单击代码将启动一个新活动以显示详细信息片段:
public static class DetailsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE) {
// If the screen is now in landscape mode, we can show the
// dialog in-line with the list so we don't need this activity.
finish();
return;
}
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
}
}
}
但是,屏幕可能足够大,可以同时显示标题列表和当前所选标题的详细信息。 若要在横向屏幕上使用此类布局,可将此替代布局放置在布局布局下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent" android:layout_height="match_parent">
<fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment"
android:id="@+id/titles" android:layout_weight="1"
android:layout_width="0px" android:layout_height="match_parent" />
<FrameLayout android:id="@+id/details" android:layout_weight="1"
android:layout_width="0px" android:layout_height="match_parent"
android:background="?android:attr/detailsElementBackground" />
</LinearLayout>
当容器存在时,标题片段将嵌入详细信息片段。 如果可以就地显示详细信息,则详细信息活动将完成。
配置更改重新创建活动时,其新布局可能会省略从 <片段标记创建的片段> 。 可以还原片段,但在布局中出现之前,它不会前进到创建的状态或创建其视图。 其 IsInLayout 属性为 false。 该示例还演示如何避免在缺少动态添加片段的容器时创建视图。
片段>标记上的<属性控制附加视图时使用的布局参数。 片段还可以分析 Android 6.0 及更高版本或 OnInflate(Activity, IAttributeSet, Bundle) Android 5.0 和 5.1 中的属性OnInflate(Context, IAttributeSet, Bundle)。 片段需要标识符,以便可以在活动重新创建后将其与上一个实例相关联。 指定 android:tag 或使用 android:id容器的视图 ID。
事务可以放置在活动的后退堆栈上。 当用户回退时,堆栈上的事务会在活动完成之前弹出。 以下片段采用整数参数并将其显示在文本视图中:
public static class CountingFragment extends Fragment {
int mNum;
/**
* Create a new instance of CountingFragment, providing "num"
* as an argument.
*/
static CountingFragment newInstance(int num) {
CountingFragment f = new CountingFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
/**
* When creating, retrieve this instance's number from its arguments.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
}
/**
* The Fragment's UI is just a simple text view showing its
* instance number.
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.hello_world, container, false);
View tv = v.findViewById(R.id.text);
((TextView)tv).setText("Fragment #" + mNum);
tv.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.gallery_thumb));
return v;
}
}
一个函数,用于创建片段的新实例,替换显示的任何当前片段实例,并将该更改推送到后台堆栈可以编写为:
void addFragmentToStack() {
mStackLevel++;
// Instantiate a new fragment.
Fragment newFragment = CountingFragment.newInstance(mStackLevel);
// Add the fragment to the activity, pushing this transaction
// on to the back stack.
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.simple_fragment, newFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
每次调用此函数后,堆栈上都会有一个新条目,然后按回会弹出它,以将用户返回到活动 UI 处于的任何以前状态。 出现或消失的片段不会为辅助功能生成系统事件。 在 Android 9.0(API 级别 28)或更高版本上,在片段的视图中设置 AccessibilityPaneTitle ,以通知辅助功能用户这些 UI 转换。
Android 参考。android.app.Fragment
本页的某些部分是根据 创建和共享的工作进行的修改,并根据 许可证中所述的条款使用。
构造函数
| 名称 | 说明 |
|---|---|
| Fragment() |
默认构造函数。 |
| Fragment(IntPtr, JniHandleOwnership) |
初始化现有 Java Native Interface 对象的托管表示形式。 |
属性
| 名称 | 说明 |
|---|---|
| Activity |
返回此片段当前关联的活动。 |
| AllowEnterTransitionOverlap |
返回退出转换和输入转换是否重叠。 - 或 - 设置退出转换和输入转换是否重叠。 |
| AllowReturnTransitionOverlap |
返回转换和重新输入转换是否重叠。 - 或 - 设置返回转换和重新输入转换是否重叠。 |
| Arguments |
返回提供给 |
| ChildFragmentManager |
返回一个专用 FragmentManager,用于在此片段中放置和管理片段。 |
| Class |
返回此 |
| Context |
|
| EnterTransition |
返回将视图移动到初始场景的转换。 - 或 - 设置将用于将视图移动到初始场景的转换。 |
| ExitTransition |
返回转换,当片段被删除、隐藏或分离时,将用于将视图移出场景,而不是弹出后堆栈。 - 或 - 设置在删除、隐藏或分离片段时,将用于将视图移出场景的过渡。如果未弹出后台堆栈,则将其隐藏或分离。 |
| FragmentManager |
返回 FragmentManager,以便与与此片段的活动关联的片段进行交互。 |
| Handle |
基础 Android 实例的句柄。 (继承自 Object) |
| Host |
返回此片段的主机对象。 |
| Id |
返回此片段已知的标识符。 |
| IsAdded |
获取片段是否具有主机并标记为已添加。 |
| IsDetached |
如果片段已从 UI 显式分离,则返回 true。 |
| IsHidden |
如果片段已被隐藏,则返回 true。 |
| IsInLayout |
获取片段是否标记为包含在当前布局中。 |
| IsRemoving |
获取片段是否标记为要删除。 |
| IsResumed |
如果片段处于恢复状态,则返回 true。 |
| IsStateSaved |
获取片段管理器是否已保存其状态。 |
| IsVisible |
如果片段当前对用户可见,则返回 true。 |
| JniIdentityHashCode |
获取为此对等方存储的Java标识哈希代码。 (继承自 Object) |
| JniManagedPeerState |
获取运行时上次分配的状态标志。 (继承自 JavaObject) |
| JniPeerMembers |
为 Android.App.Fragment 提供 JNI 绑定基础结构。 |
| LayoutInflater |
返回用于扩充此片段视图的缓存 LayoutInflater。 |
| LoaderManager |
返回此片段的 LoaderManager,根据需要创建它。 |
| ParentFragment |
返回包含此片段的父片段。 |
| PeerReference |
获取此Java对等方的 JNI 对象引用。 (继承自 Object) |
| ReenterTransition |
返回由于弹出后退堆栈而返回时,将用于将视图移动到场景中的转换。 - 或 - 设置在返回时用于在返回时将视图移动到场景中的切换,因为弹出后堆栈。 |
| Resources |
获取与片段的主机关联的资源。 |
| RetainInstance |
控制片段实例是否在活动重新创建(例如从配置更改)中保留。 |
| ReturnTransition |
返回转换,当片段准备删除、隐藏或分离时,将用于将视图移出场景,因为弹出后堆栈。 - 或 - 设置在片段准备删除、隐藏或分离时用于将视图移出场景的过渡,因为弹出后堆栈。 |
| SharedElementEnterTransition |
返回将用于传输到内容场景的共享元素的转换。 - 或 - 设置将用于传输到内容场景的共享元素的转换。 |
| SharedElementReturnTransition |
返回转换,该转换将用于在后台堆栈弹出期间传输回的共享元素。 - 或 - 设置转换,该转换将用于在后台堆栈弹出期间传输回的共享元素。 |
| Tag |
获取片段的标记名称(如果指定)。 |
| TargetFragment |
返回按 SetTargetFragment(Fragment, Int32). 设置的目标片段。 |
| TargetRequestCode |
返回由 SetTargetFragment(Fragment, Int32). 设置的目标请求代码。 |
| ThresholdClass |
为 Android.App.Fragment 提供 JNI 绑定基础结构。 |
| ThresholdType |
为 Android.App.Fragment 提供 JNI 绑定基础结构。 |
| UserVisibleHint |
向系统设置一个提示,说明此片段的 UI 当前是否对用户可见。 |
| View |
获取片段布局(返回者 OnCreateView(LayoutInflater, ViewGroup, Bundle))的根视图(如果提供)。 |
方法
显式接口实现
| 名称 | 说明 |
|---|---|
| IJavaPeerable.Disposed() |
将此对等方标记为已释放,并将 |
| IJavaPeerable.Finalized() |
将此对等方标记为已释放,并将 |
| IJavaPeerable.JniObjectReferenceControlBlock |
获取此对等方使用的本机控制块指针。 (继承自 JavaObject) |
| IJavaPeerable.SetJniIdentityHashCode(Int32) |
存储运行时提供的标识哈希代码。 (继承自 JavaObject) |
| IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) |
替换存储的托管对等状态标志。 (继承自 JavaObject) |
| IJavaPeerable.SetPeerReference(JniObjectReference) |
更新对等引用,并在引用无效时释放已释放的对等方控制块。 (继承自 JavaObject) |
| IJavaPeerable.UnregisterFromRuntime() |
从运行时的Java对象查找中删除此实例。 |
扩展方法
| 名称 | 说明 |
|---|---|
| GetJniTypeName(IJavaPeerable) |
获取实例 |
| JavaAs<TResult>(IJavaPeerable) |
尝试强制 |
| JavaCast<TResult>(IJavaObject) |
执行 Android 运行时检查的类型转换。 |
| JavaCast<TResult>(IJavaObject) |
重复使用兼容的托管对等,或获取请求类型的包装器。 |
| TryJavaCast<TResult>(IJavaPeerable, TResult) |
尝试强制 |