2013-03-27 44 views
0

我的舊版Android應用程序使用4種不同的活動(FirstActivity => FourthActivity,以及相應的xml activity_first => activity_fourth),並且該應用程序可以在使用這些活動之間來回切換Intent。最近我想更改用戶界面以使用ViewPagerIndicator。我已經實現了4個片段是這樣的:將片段附加到Android中的活動

public class FirstFragment extends Fragment{ 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ 
     return inflater.inflate(R.layout.activity_first, null); 
    } 
} 

的問題是,我怎麼能遷移從FirstActivity所有的業務代碼FirstFragment?我只需要找到onCreate,onDestroy,onStart ...的等價物並複製/粘貼代碼(在適當的位置添加getActivity(),getView())?有沒有簡單的方法將片段附加到活動中以避免這樣做?

+1

我發現[this](http://www.vogella.com/articles/AndroidFragments/article.html)網站有助於學習片段。另請查看[here](http://developer.android.com/guide/components/fragments.html)瞭解片段的生命週期。片段具有與Activity相同的onCreate,onResume,onStop等,但它也有更多。 – TronicZomB 2013-03-27 12:20:03

回答

3

最簡單的方法是將您在個人活動中使用的代碼在onCreate()之間遷移到onActivityCreated()中。然後使用支持活動的onCreate()方法中的片段事務將片段添加到活動中。 Android文檔給出了一個很好的步驟,通過如何完成這個here,完整的示例代碼。如果有一些困惑你要做到以下幾點在你的基本活動:

獲取新FragmentManager

FragmentManager fragmentManager = getFragmentManager(); 
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 

創建片段

ExampleFragment fragment = new ExampleFragment(); 

的新實例添加一個片段給您FragmentManager

fragmentTransaction.add(R.id.fragment_container, fragment); 
fragmentTransaction.commit(); 

Ther e有多種不同的使用片段的方式 - 例如ViewPagerViewSwitcher需要不同的實現,但這聽起來像是它解決了你想要做的事情。

相關問題