纵向模式的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
android:id="@+id/titles"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="edu.dartmouth.cs.FragmentLayout$TitlesFragment" />
</FrameLayout>
在横向模式下,单个活动 (FragmentLayout) 处理两个片段。我们还将考虑以编程方式插入片段。考虑景观 res/layout-land/fragment_layout。
横屏模式的fragment_layout.xml是:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
android:orientation="horizontal" >
<fragment
android:id="@+id/titles"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
class="edu.dartmouth.cs.FragmentLayout$TitlesFragment" />
<FrameLayout
android:id="@+id/details"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="?android:attr/detailsElementBackground" />
</LinearLayout>
如果您在 TitlesFragment: onActivityCreated() 中注释掉下面显示的代码行(当 FragmentLayout onCreate() 返回时调用),那么您将在上面的 frame_layout 中看到加载时的空白。如果没有重新添加该行,则在用户从列表中选择一个项目之前,不会将 DetailsFragment 加载到其中 - 此时会创建 DetailsFragment 并将其放入 FrameLayout。
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
**snippet**
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);
} else {
FragmentLayout(主要活动)在 onCreate() 期间以通常的方式应用布局:
public class FragmentLayout extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// root view inflated
setContentView(R.layout.fragment_layout);
}
当用户单击 ListFragment 中的一个项目时,会调用 onListItemClick() 回调,然后调用 showDetails(position) 来启动
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getActivity(),
"onListItemClick position is" + position, Toast.LENGTH_LONG)
.show();
showDetails(position);
}
标题片段
片段使用辅助函数来显示所选项目的详细信息。
public static class TitlesFragment extends ListFragment {
boolean mDualPane;
int mCurCheckPosition = 0;
// onActivityCreated() is called when the activity's onCreate() method
// has returned.
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// You can use getActivity(), which returns the activity associated
// with a fragment.
// The activity is a context (since Activity extends Context) .
Toast.makeText(getActivity(), "TitlesFragment:onActivityCreated",
Toast.LENGTH_LONG).show();
// Populate list with our static array of titles in list in the
// Shakespeare class
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.
// R.id.details relates to the res/layout-land/fragment_layout.xml
// This is first created when the phone is switched to landscape
// mode
View detailsFrame = getActivity().findViewById(R.id.details);
Toast.makeText(getActivity(), "detailsFrame " + detailsFrame,
Toast.LENGTH_LONG).show();
// Check that a view exists and is visible
// A view is visible (0) on the screen; the default value.
// It can also be invisible and hidden, as if the view had not been
// added.
//
mDualPane = detailsFrame != null
&& detailsFrame.getVisibility() == View.VISIBLE;
Toast.makeText(getActivity(), "mDualPane " + mDualPane,
Toast.LENGTH_LONG).show();
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);
} else {
// We also highlight in uni-pane just for fun
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setItemChecked(mCurCheckPosition, true);
}
}
管理方向翻转之间的状态
该应用程序会跟踪当前选中的选择,因此当它恢复它时 - 再次以横向方式将其作为片段生命周期中使用 onSaveInstanceState() 突出显示的最后一个位置。片段保存其当前的动态状态,因此稍后可以在重新启动其进程的新实例中重建它。如果稍后需要创建片段的新实例,那么您在此处放置在 Bundle 中的数据将在提供给 onCreate(Bundle)、onCreateView(LayoutInflater, ViewGroup, Bundle) 和 onActivityCreated(Bundle) 的 Bundle 中可用。在代码中,新片段恢复 onActivityCreated() 中的状态。这里的状态只是 mCurCheckPosition。
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Toast.makeText(getActivity(), "onSaveInstanceState",
Toast.LENGTH_LONG).show();
outState.putInt("curChoice", mCurCheckPosition);
}
FragmentManager 和 Fragment 事务
帮助函数 (showDetails(position)) 显示所选项目的详细信息,方法是在当前 UI 中就地显示片段,或启动显示片段的全新活动。
void showDetails(int index) {
mCurCheckPosition = index;
// The basic design is mutli-pane (landscape on the phone) allows us
// to display both fragments (titles and details) with in the same
// activity; that is FragmentLayout -- one activity with two
// fragments.
// Else, it's single-pane (portrait on the phone) and we fire
// another activity to render the details fragment - two activities
// each with its own fragment .
//
if (mDualPane) {
// We can display everything in-place with fragments, so update
// the list to highlight the selected item and show the data.
// We keep highlighted the current selection
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);
Toast.makeText(getActivity(),
"showDetails dual-pane: create and replace fragment",
Toast.LENGTH_LONG).show();
// 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.
// That is: if this is a single-pane (e.g., portrait mode on a
// phone) then fire DetailsActivity to display the details
// fragment
// Create an intent for starting the DetailsActivity
Intent intent = new Intent();
// explicitly set the activity context and class
// associated with the intent (context, class)
intent.setClass(getActivity(), DetailsActivity.class);
// pass the current position
intent.putExtra("index", index);
startActivity(intent);
}
}
DetailsActivity:纵向模式处理
如前所述,如果用户单击列表项并且当前布局不包括 R.id.details 视图(DetailsFragment 执行此操作),则应用程序启动 DetailsActivity 活动以显示该项目的内容。辅助函数在横向创建一个新的片段以在纵向绘制细节启动一个活动(DetailsActivity)来管理细节片段 - 即创建一个新的DetailsFragment并使用FragmentManager将其添加到根视图,如下所示。 DetailsActivity 嵌入 DetailsFragment 以在屏幕为纵向时显示选定的播放摘要:
// 这是一个辅助活动,用于显示用户在
// 屏幕不够大,无法在一个活动中全部显示。
公共静态类 DetailsActivity 扩展 Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(this, "DetailsActivity", Toast.LENGTH_SHORT).show();
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.
// create fragment
DetailsFragment details = new DetailsFragment();
// get and set the position input by user (i.e., "index")
// which is the construction arguments for this fragment
details.setArguments(getIntent().getExtras());
//
getFragmentManager().beginTransaction()
.add(android.R.id.content, details).commit();
}
}
}
详细信息片段
首先创建片段。片段生命周期确保 onCreateView() 为片段构建布局。它使用 textview 构建片段 - text.setText(Shakespeare.DIALOGUE[getShownIndex()]) - 并将其附加到滚动条 (ScrollView) 并返回(并呈现)绘制的视图。
// This is the secondary fragment, displaying the details of a particular
// item.
public static class DetailsFragment extends Fragment {
**snippet**
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
// The system calls this when it's time for the fragment to draw its
// user interface for the first time. To draw a UI for your fragment,
// you must return a View from this method that is the root of your
// fragment's layout. You can return null if the fragment does not
// provide a UI.
// We create the UI with a scrollview and text and return a reference to
// the scoller which is then drawn to the screen
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
**snippet**
// programmatically create a scrollview and textview for the text in
// the container/fragment layout. Set up the properties and add the view
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;
}
}