我正在寻找一种真正的方法来避免在屏幕旋转后重新创建片段
if (container == null) { return null; }
并没有真正避免重新创建 Fragment。(如下图所示)
官方 Fragment 开发者指南在哪里?
我们所关注的官方指南位于http://developer.android.com/guide/components/fragments.html。部分示例代码位于指南的底部。据我所知,完整的示例代码可在 Android 3.0 (API 11) 下的“Samples for SDK”中找到。此外,我对示例代码进行了最小的修改,使其在 API 10 中运行,并添加了一些调试消息,这些消息包含在这个问题的底部。
在哪里R.id.a_item
?
您可以在开发人员指南示例中找到以下代码存根:
if (index == 0) {
ft.replace(R.id.details, details);
} else {
ft.replace(R.id.a_item, details);
}
我在互联网上进行了一些搜索,发现其他一些也与R.id.a_item
. 在检查 API 11 中的示例后,我很确定这只是一个毫无意义的错字。样本中根本没有这样的行。
避免屏幕旋转后重新创建片段的真正方法?
网络上有许多现有的讨论。但似乎还没有一个“真正的”解决方案。
我在下面的代码中添加了许多调试消息,以跟踪DetailsFragment
类的生命周期。尝试(1)以纵向模式启动程序,然后(2)将设备转为横向模式,然后(3)将其转回纵向,(4)再次横向,(5)再次返回纵向,最后(6) 放弃它。我们将收到以下调试消息:
(1) 以纵向模式启动
TitlesFragment.onCreate() Bundle=null
只有TitlesFragment
被创建。DetailsFragment
尚未显示。
(2) 转成横向模式
TitlesFragment.onCreate() Bundle=Bundle[{shownChoice=-1, android:view_state=android.util.SparseArray@4051d3a8, curChoice=0}]
DetailsFragment.onAttach() Activity=com.example.android.apis.app.FragmentLayout @4051d640
DetailsFragment.onCreate() Bundle=null
DetailsFragment.onCreateView() Activity=android.widget.FrameLayout@4050df68
DetailsFragment.onActivityCreated() Bundle=null
DetailsFragment.onStart()
DetailsFragment.onResume()
首先,TitlesFragment
是重新创建的(使用 savedInstanceState Bundle)。然后DetailsFragment
是动态创建的(通过TitlesFragment.onActivityCreated()
、调用showDetails()
、使用FragmentTransaction
)。
(3) 回到纵向模式
DetailsFragment.onPause()
DetailsFragment.onStop()
DetailsFragment.onDestroyView()
DetailsFragment.onDestroy()
DetailsFragment.onDetach()
DetailsFragment.onAttach() Activity=com.example.android.apis.app.FragmentLayout@40527f70
DetailsFragment.onCreate() Bundle=null
TitlesFragment.onCreate() Bundle=Bundle[{shownChoice=0, android:view_state=android.util.SparseArray@405144b0, curChoice=0}]
DetailsFragment.onCreateView() Activity=null
DetailsFragment.onActivityCreated() Bundle=null
DetailsFragment.onStart()
DetailsFragment.onResume()
这是我们关注的第一个地方,即真正的避免再创造的方法。
这是因为DetailsFragment
之前已附加到layout-land/fragment_layout.xml
<FrameLayout>
ViewGroup
横向模式。它有一个 ID ( R.id.details
)。当屏幕旋转时,ViewGroup
作为 的实例的DetailsFragment
被保存到 Activity FragmentLayout 的 Bundle 中,在 FragmentLayout 的 onSaveInstanceState() 中。进入纵向模式后,将DetailsFragment
重新创建。但在纵向模式下不需要。
在示例中(以及许多其他人建议的),DetailsFragment
该类使用if (container == null) { return null; }
inonCreateView()
来避免DetailsFragment
以纵向模式显示。但是,如上面的调试消息所示,DetailsFragment
在后台仍然存在,作为一个孤儿,拥有所有生命周期方法调用。
(4)再次进入横向模式
DetailsFragment.onPause()
DetailsFragment.onStop()
DetailsFragment.onDestroyView()
DetailsFragment.onDestroy()
DetailsFragment.onDetach()
DetailsFragment.onAttach() Activity=com.example.android.apis.app.FragmentLayout@4052c7d8
DetailsFragment.onCreate() Bundle=null
TitlesFragment.onCreate() Bundle=Bundle[{shownChoice=0, android:view_state=android.util.SparseArray@40521b80, curChoice=0}]
DetailsFragment.onCreateView() Activity=android.widget.FrameLayout@40525270
DetailsFragment。 onActivityCreated() Bundle=null
DetailsFragment.onStart()
DetailsFragment.onResume()
请注意,在前 5 行中,DetailsFragment
完成了其生命周期状态,然后销毁并分离。
这进一步证明了该if (container == null) { return null; }
方法并不是真正摆脱DetailsFragment
实例的方法。(我认为垃圾收集器会摧毁这个悬空的孩子,但事实并非如此。这是因为 Android 确实允许悬空的片段。参考:添加没有 UI 的片段。)
据我了解,从第 6 行开始,它应该是DetailsFragment
由 创建的新实例TitlesFragment
,就像在 (2) 中所做的那样。但我无法解释为什么DetailsFragment
'sonAttach()
和onCreate()
方法在TitlesFragment
's之前被调用onCreate()
。
但是'snull
中的 Bundle会证明它是一个新实例。DetailsFragment
onCreate()
据我了解,之前的悬空DetailsFragment
实例这次不会重新创建,因为它没有 ID。所以它没有将视图层次结构自动保存到 savedInstanceState 包中。
(5) 再次回到人像模式
DetailsFragment.onPause()
DetailsFragment.onStop()
DetailsFragment.onDestroyView()
DetailsFragment.onDestroy()
DetailsFragment.onDetach()
DetailsFragment.onAttach() Activity=com.example.android.apis.app.FragmentLayout@4052d7d8
DetailsFragment.onCreate() Bundle=null
TitlesFragment.onCreate() Bundle=Bundle[{shownChoice=0, android:view_state=android.util.SparseArray@40534e30, curChoice=0}]
DetailsFragment.onCreateView() Activity=null
DetailsFragment.onActivityCreated() Bundle=null
DetailsFragment.onStart()
DetailsFragment.onResume()
请注意,所有生命周期回调都与(3)中的第一次返回纵向相同,除了不同的Activity ID (40527f70 vs 4052d7d8)
and view_state Bundle (405144b0 vs 40534e30)
。这是合理的。FragmentLayout Activity 和 Instance State Bundle 都被重新创建。
(6)退出(按 BACK 按钮)
I/System.out(29845):DetailsFragment.onPause() I/System.out(29845):DetailsFragment.onStop() I/System.out(29845):DetailsFragment.onDestroyView() I/System.out(29845) : DetailsFragment.onDestroy() I/System.out(29845): DetailsFragment.onDetach()
如果我们能把 in 去掉就DetailsFragment
完美了FragmentLayout
。onDestroy()
但是FragmentTransaction
'remove()
方法需要在onSaveInstanceState()
. 但是,无法确定它是否是屏幕旋转onSaveInstanceState()
。
无论如何也无法删除DetailsFragment
in FragmentLayout
。onSaveInstanceState()
首先,如果DetailsFragment
只是部分被对话框遮挡,它将在背景中消失。此外,在被对话框遮挡或切换活动的情况下,既onCreate(Bundle)
不会也onRestoreInstanceState(Bundle)
不会再次调用。因此,我们没有地方可以恢复 Fragment(并从 Bundle 中检索数据)。
源代码和文件
片段布局.java
package com.example.android.apis.app;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
public class FragmentLayout extends FragmentActivity {
private final static class Shakespeare {
public static final String[] TITLES = { "Love", "Hate", "One", "Day" };
public static final String[] DIALOGUE = {
"Love Love Love Love Love",
"Hate Hate Hate Hate Hate",
"One One One One One",
"Day Day Day Day Day" };
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_layout);
}
public static class DetailsActivity extends FragmentActivity {
@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());
getSupportFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
}
}
}
public static class TitlesFragment extends ListFragment {
boolean mDualPane;
int mCurCheckPosition = 0;
int mShownCheckPosition = -1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println(getClass().getSimpleName() + ".onCreate() Bundle=" +
(savedInstanceState == null ? null : savedInstanceState));
}
@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_1, Shakespeare.TITLES));
// API 11:android.R.layout.simple_list_item_activated_1
// 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);
mShownCheckPosition = savedInstanceState.getInt("shownChoice", -1);
}
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);
outState.putInt("shownChoice", mShownCheckPosition);
}
@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);
if (mShownCheckPosition != mCurCheckPosition) {
// If we are not currently showing a fragment for the new
// position, we need to create and install a new one.
DetailsFragment df = 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, df);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
mShownCheckPosition = index;
}
} 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;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println(getClass().getSimpleName() + ".onCreate() Bundle=" +
(savedInstanceState == null ? null : savedInstanceState));
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
System.out.println(getClass().getSimpleName() + ".onAttach() Activity=" +
(activity == null ? null : activity));
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
System.out.println(getClass().getSimpleName() + ".onActivityCreated() Bundle=" +
(savedInstanceState == null ? null : savedInstanceState));
}
@Override
public void onStart() { super.onStart(); System.out.println(getClass().getSimpleName() + ".onStart()"); }
@Override
public void onResume() { super.onResume(); System.out.println(getClass().getSimpleName() + ".onResume()"); }
@Override
public void onPause() { super.onPause(); System.out.println(getClass().getSimpleName() + ".onPause()"); }
@Override
public void onStop() { super.onStop(); System.out.println(getClass().getSimpleName() + ".onStop()"); }
@Override
public void onDestroyView() { super.onDestroyView(); System.out.println(getClass().getSimpleName() + ".onDestroyView()"); }
@Override
public void onDestroy() { super.onDestroy(); System.out.println(getClass().getSimpleName() + ".onDestroy()"); }
@Override
public void onDetach() { super.onDetach(); System.out.println(getClass().getSimpleName() + ".onDetach()"); }
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
System.out.println(getClass().getSimpleName() + ".onCreateView() Activity=" +
(container == null ? null : container));
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[getArguments().getInt("index", 0)]);
return scroller;
}
}
}
布局/fragment_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<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>
布局土地/fragment_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:baselineAligned="false"
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" />
<!-- API 11:android:background="?android:attr/detailsElementBackground" -->
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.apis.app"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="4"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.android.apis.app.FragmentLayout"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.android.apis.app.FragmentLayout$DetailsActivity"
android:label="@string/app_name" >
</activity>
</application>
</manifest>