Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Update</strong>: I have quickly written some example code, this code doesn't handle orientation change well. This is something you will have to figure out yourself. There a numerous ways of handling this and I'm not 100% sure what would be the most ideal. This sample code should get you started. If you figured out the correct way to handle orientation change comment below or edit this post.</p> <p><strong>MainActivity:</strong></p> <pre><code>public class MainActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) { getSupportFragmentManager().beginTransaction() .add(android.R.id.content, new ViewPagerFragment()) .commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } </code></pre> <p><strong>ViewPagerFragment:</strong></p> <pre><code>public class ViewPagerFragment extends Fragment { private ViewPager mPager; private PagerAdapter mPagerAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_pager, container,false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mPager = (ViewPager) view.findViewById(R.id.pager); mPagerAdapter = new CustomPagerAdapter(getChildFragmentManager()); mPager.setAdapter(mPagerAdapter); } private class CustomPagerAdapter extends FragmentStatePagerAdapter { public CustomPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { return new ViewPagerPageFragment(); } @Override public int getCount() { return 10; } } } </code></pre> <p>ViewPagerPageFragment:</p> <pre><code>public class ViewPagerPageFragment extends Fragment{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_page,container,false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); Random rnd = new Random(); int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)); view.findViewById(R.id.fragment_page_wrapper).setBackgroundColor(color); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload