Fragment Android Club 2015
Agenda Fragment Static fragment Dynamic fragment ViewPager
What is fragment? Fragment – used to show part of Activity’s UI. Introduced in Android 3.0 Honeycomb Initially was developed for tablets
Why to use fragment? 1. Form-factor 2. Passing information 3. Tabs & spinner 4. Swipe based navigation
Static fragment: example
Static fragment: practice Create new Activity It should contain three fragments FirstFragment: bg: purple, contains: ToggleButton SecondFragment: bg: white, contains: RatingBar ThirdFragment: bg: brown, contains: EditText
Dynamic fragment: 4 steps 1. Reference FragmentManager 2. Begin FragmentTransaction 3. Add fragment to transaction 4. Commit
Dynamic fragment: example FragmentManager manager = getFragmentManager(); FragmentTransaction transaction = manager.beginTransaction(); RedFragment fragment = new RedFragment(); transaction.add(R.id.flFragments, fragment); transaction.commit();
Dynamic fragment: practice Create three buttons for FirstFragment, SecondFragment, ThirdFragment Change fragments dynamically on click each button
ViewPager adapter: example public class MyPagerAdapter extends FragmentStatePagerAdapter { public MyPagerAdapter(FragmentManager fm) { super(fm); public Fragment getItem(int position) { switch(position) { case 0: return new RedFragment(); case 1: return new YellowFragment(); } return null; public int getCount() { return 2; } }
android.support.v4.view.Vie wPager: example ViewPager vpPager = (ViewPager) findViewById(R.id.vpPager); MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManag er()); vpPager.setAdapter(adapter);
ViewPager: practice Create new ViewPager Create new FragmentStatePagerAdapter for ViewPager Set FragmentStatePagerAdapter as ViewPager’s adapter
Homework 1: static fragment Create new activity In activity’s layout add 5 fragments Each fragment’s height should 100dp Each fragment should contain different views
Homework 2: dynamic fragment Create new Activity Activity’s layout should contain 5 buttons and one framelayout On click each button, should show separate button It should look like Facebook app
Homework 3: viewpager Create new Activity Put one ViewPager Create adapter for it ViewPager should show images as slideshow. 10 images!
Questions? Any quesitons?
Thank you! Thank you very much for your attention!