1. 程式人生 > >How To Create Android Swipe Views With Tabs

How To Create Android Swipe Views With Tabs

Android swipe views provide lateral navigation between sibling screens such as tabs with a horizontal finger gesture (a pattern sometimes known as horizontal paging). In this post, I will be using a simple android app that I created this past weekend to show you how to create android swipe views. If you have used many android apps, there is a good chance you have seen android swipe views. If not, well, this is your chance to try them. So, here is how the app looks like using swipe views.

android swipe views

What you need to create android swipe views

In order to create functioning android swipe views, you will need the following pieces at the least:

  • The android support v4 library – located in your android sdk extras folder.
  • A layout file that contains the view pager component.
  • A tabs pager adapter to manage your tabs and load the appropriate fragment into view.
  • At least one fragment to display in view when a user swipes the views.
  • An Activity that will be the main activity showing tabs.

So, let us do this so you can go out there and make the world a better place

In that same order, let us start with our main layout file.

main.xml

NOTE: the code in this xml file is not formatted correctly. I know, I need a better syntax highlighter – am planning on getting one. I apologize.

12345678910111213141516 <?xml version="1.0"encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"><android.support.v4.view.ViewPagerandroid:id="@+id/pager"android:layout_width="wrap_content"android:layout_height="wrap_content"></android><LinearLayout>

Amazingly (if that is amazing), that is all you need for that file. Pay close attention to the id because we will need it soon in our activity. Next, let us create our tabs pager adapter like this:

TabsPagerAdapter.java

123456789101112131415161718192021222324252627282930313233 publicclassTabsPagerAdapterextendsFragmentPagerAdapter{publicTabsPagerAdapter(FragmentManager fm){super(fm);}@Overridepublicandroid.support.v4.app.Fragment getItem(intindex){switch(index){case0:returnnewCaptureMomentFragment();case1:returnnewUploadMomentFragment();case2:returnnewStatsMomentsFragment();}returnnull;}@OverridepublicintgetCount(){return3;}}

As you can see, the above adapter will keep track of which tab is currently selected and loads or returns the right fragment. Pretty simple and awesome too. There are other methods from the base class that you can override but for now, those two are the ones we need. The getCount() method must return the number that represents the number of your tabs in the android swipe views.

Next, let us create one fragment – I will use the example from my app. You can, if you wish, create the other two fragments if you are following along.

CaptureMomentFragments.java

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 publicclassCaptureMomentFragment extendsFragment implementsView.OnClickListener{protectedActivity mActivity;privateImageView mCamera;privateTextView intro;@OverridepublicvoidonAttach(Activity act){super.onAttach(act);mActivity=act;}@OverridepublicvoidonCreate(Bundle saveInstanceState){super.onCreate(saveInstanceState);}@OverridepublicvoidonActivityCreated(Bundle saveInstanceState){super.onActivityCreated(saveInstanceState);}@OverridepublicView onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){View view=inflater.inflate(R.layout.capture_photo_fragment,container,false);intro=(TextView)view.findViewById(R.id.intro);Typeface typeFace=Typeface.createFromAsset(mActivity.getAssets(),"fonts/ArchitectsDaughter.ttf");intro.setTypeface(typeFace);intro.setText(Html.fromHtml(mActivity.getString(R.string.introd)));mCamera=(ImageView)view.findViewById(R.id.camera);mCamera.setOnClickListener(this);returnview;}@OverridepublicvoidonClick(Viewv){//do whatever you want here}}

Here, I am basically inflating and returning a view that contains a text view and an image view that holds the camera button as shown in the photo above. Remember that when you extend Fragment, it has to be the one from the support library. Everything else here should be self-explanatory. That includes creating the layout for your fragment.

Next, let us put it all together and see how we can create android swipe views by crafting our main activity.

MainSwipeActivity.java

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 publicclassMainSwipeActivity extendsFragmentActivity implementsActionBar.TabListener{privateViewPager viewPager;privateActionBar actionBar;privateTabsPagerAdapter mAdapter;@OverridepublicvoidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_ACTION_BAR);setContentView(R.layout.gd_pager);getActionBar().setDisplayHomeAsUpEnabled(true);viewPager=(ViewPager)findViewById(R.id.pager);actionBar=getActionBar();actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);String[]tabs=newString[]{"capture","upload","stats"};Typeface typeFace=Typeface.createFromAsset(getAssets(),"fonts/ArchitectsDaughter.ttf");for(Stringtab:tabs){TextViewt=newTextView(this);t.setAllCaps(true);t.setLayoutParams(newLinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT,Gravity.CENTER_VERTICAL));t.setGravity(Gravity.CENTER_VERTICAL);t.setTextColor(Color.WHITE);t.setText(tab);t.setTypeface(typeFace);actionBar.addTab(actionBar.newTab().setCustomView(t).setTabListener(this));}mAdapter=newTabsPagerAdapter(getSupportFragmentManager());viewPager.setAdapter(mAdapter);}@OverridepublicvoidonTabSelected(ActionBar.Tab tab,FragmentTransaction ft){viewPager.setCurrentItem(tab.getPosition());viewPager.setOnPageChangeListener(newViewPager.OnPageChangeListener(){@OverridepublicvoidonPageSelected(intposition){actionBar.setSelectedNavigationItem(position);}@OverridepublicvoidonPageScrolled(intarg0,floatarg1,intarg2){}@OverridepublicvoidonPageScrollStateChanged(intarg0){}});}@OverridepublicvoidonTabUnselected(ActionBar.Tab tab,FragmentTransaction ft){}@OverridepublicvoidonTabReselected(ActionBar.Tab tab,FragmentTransaction ft){}}

Implementing the ActionBar.TabListener interface enables us to load the correct view when a user swipes or touches one of the tabs. We then request window feature (Window.FEATURE_ACTION_BAR) – you must do this before setting content view (the view pager layout we created first).

We then have this line:

actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

which does exactly what it says. Enables tabs mode in your app.

Your android swipe views will most likely have titles to tell the users what they are getting into. So, store those in a simple list of strings.

You then loop through your list and create new tabs. I added some fonts of my own to make it look different – I like being different.

Next, you create a new instance of your TabsPagerAdapter and call the setAdapter method on the viewPager passing it the adapter instance. It takes a fragment manager – that is how it sets fragments in view.

Everything else above should be self-explanatory. And that is all you need to have working android swipe views in your awesome app. You can do more than that obviously but at least you now know how to.

Summary

If this tutorial on how to create android swipe views helped you learn something, please consider sharing this post using the buttons below. And always remember to stay awesome. Thank you for stopping by. Oh, you can always read more about android swipe views here.