[英]Fragments on 2.x vs. 3.x devices
在完成許多Android 2.x應用程序之后,我現在開始使用兼容性包在2.x和3.x設備上使用Fragments。
到現在為止,我所有的布局都屬於res / layoutxxx文件夾的一部分,不需要在src代碼中進行任何手動更改。
當查看如下所示的Fragment示例時,在src代碼中始終會在不同設備功能之間做出決定。 這真的需要嗎? 我不明白為什么新的Fragment設計要求針對不同的設備/布局/方向進行動態更改。
所以我的問題是:我想像往常一樣將所有不同的布局放在其res / layout文件夾中,讓Android進行其余工作-甚至是2窗格(在平板電腦上)或1窗格(在手機上)顯示。 有某種包裝嗎?
//
// 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);
}
}
如果支持各種屏幕尺寸,則在某些屏幕上並排有2個片段,而在其他(較小的)屏幕上,只有一個片段(加載器/充氣的)。
如果您不使用片段,則同樣的邏輯也適用,只要讓Android為特定的屏幕配置選擇不同的布局即可。
結果是,使用相同的代碼,取決於設備規格,您可能會存在某些屏幕元素,或者不存在,並且您的代碼必須通過有條件地檢查給定元素是否存在(膨脹)來應對這種情況。
這樣,您可以為各種設備提供特定的使用體驗。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.