我同意教程非常简化。他们只是介绍Fragments
,但我不同意建议的模式。
我也同意在许多活动中复制应用程序的逻辑不是一个好主意(请参阅维基百科上的 DRY 原则)。
ActionBarSherlock
我更喜欢Fragments Demo 应用程序使用的模式(在此处下载和源代码)。与问题中提到的教程最匹配的演示是应用程序中称为“布局”的演示;或FragmentLayoutSupport
在源代码中。
Activity
在此演示中,逻辑已从Fragment
. 实际上包含更改片段的TitlesFragment
逻辑。这样,每个Activity就很简单了。复制许多非常简单的活动,其中没有任何逻辑在活动内部,这使得它非常简单。
通过将逻辑放入 Fragments 中,无需多次编写代码;无论将 Fragment 放入哪个 Activity,它都可用。这使它成为比基本教程建议的模式更强大的模式。
/**
* 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);
}
}
ABS模式的另一个优点是您最终不会得到包含大量逻辑的 Tablet Activity,这意味着您可以节省内存。教程模式可以在更复杂的应用程序中导致非常大的主要活动;因为它需要随时处理放置在其中的所有片段的逻辑。
总的来说,不要认为它是被迫使用许多活动。可以将其视为有机会将您的代码拆分为许多片段,并在使用它们时节省内存。