Android learning Demo (17) about ViewPager and Fragment

Source: Internet
Author: User

Many times, an application has multiple function points, which are classified into different categories. Such a requirement exists. Different la s display different functions, fragment and ViewPager are a good helper.

Fragment is a feature provided after 3.0. Therefore, if you want to use Fragment before 3.x, you need to use the support v4 package.

After upgrading to the latest ADT version in Eclipse, you will find that Android projects created using Wizard use Fragment by default as the main logical window for transaction processing, the Activity does not do this anymore. This may be because Android wants to use Fragment forcibly. It tries to distribute the control of different business logic to different Fragment to reduce the Coupling Degree of the program.

Today's Demo shows how to apply Fragment and ViewPager to display different groups. The specific effect can be viewed first:

As shown in the following figure:

1) There are two pages on the interface. One is to display the running applications, the other is to display the running services, which are displayed by two Fragment.

2) There are two buttons Under the screen. With these two buttons, you can switch to different Fragment.

3) ViewPager serves as the Fragment container. You can switch between different Fragment containers by swiping the left and right.

Next, let's take a look at some key implementations:

Layout file on the main interface
1) ViewPager2) A RadioGroup contains two RadioButton instances and N Fragment instances. Because the RadioButton in the RadioGroup is mutually exclusive, just as we only need to have one Fragment selected and displayed at a certain time point. Two Fragment
As for the specific content of the two Fragment items, you can check the source code. FragmentPagerAdapter each ViewPager requires a PagerAdapter for the data source. If it is to display an image, it is a PagerAdapter for the image. If it is to display Fragment, of course there is a PagerAdapter for Fragment. Android provides two pageradapters for Fragment. Here we only need to use FragmentPagerAdapter. The Code is as follows:
class KickerFragmentAdapter extends FragmentPagerAdapter {private Context mContext;public KickerFragmentAdapter(FragmentManager fm, Context context) {super(fm);mContext = context;}@Overridepublic Fragment getItem(int arg0) {return Fragment.instantiate(mContext, fragmetns[arg0]);}@Overridepublic int getCount() {return fragmetns.length;}}

The Code logic of the FragmentPagerAdapter is very simple. It is similar to the general BaseAdapter. It mainly has three methods that must be implemented: 1) constructor with FragmentManager. To use the Support package, it must be called as follows:
KickerFragmentAdapter adpater = new KickerFragmentAdapter(getSupportFragmentManager(), this);

2) The getItem method uses the Fragment corresponding to the Fragment. instantiate method in each method. The second parameter fname is the class name corresponding to the Fragment, as shown below:
private String[] fragmetns = new String[] {RunningAppFragment.class.getName(),RunningServiceFragment.class.getName() };

3) getCount: returns the number of Pager instances.
To echo the following RadioGroup, OnPageChangeListener and OnCheckedChangeListener also need to add corresponding response functions to ViewPager and RadioGroup, as shown below:
private OnPageChangeListener onPageChangeListener = new OnPageChangeListener() {@Overridepublic void onPageSelected(int arg0) {mCurrentFragment = arg0;((RadioButton) rgTabButtons.getChildAt(arg0)).setChecked(true);}@Overridepublic void onPageScrolled(int arg0, float arg1, int arg2) {}@Overridepublic void onPageScrollStateChanged(int arg0) {}};private OnCheckedChangeListener onCheckedChangeListener = new OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(RadioGroup group, int checkedId) {int checkedItem = 0;switch (checkedId) {case = 0;break;case = 1;break;}vpContainer.setCurrentItem(checkedItem);mCurrentFragment = checkedItem;}};

The main functions here are as follows: 1) When sliding to different Fragment in ViewPager, the following RadioGroup will change. 2) When you click the RadioGroup below, you must locate the corresponding fragment in ViewPager.
In order to communicate with the Activity, the custom Listener must define interfaces for different Fragment, and then implement this interface in the Activity through the function of the callback function, it can make changes in Fragment affect the Activity at the same time, as shown below, in RunningAppFragment. in java:
public interface OnRunningAppRefreshListener {public void onRunningAppRefreshed();}

At the same time, the Activity must implement this interface as follows:
public class KickerMainActivity extends ActionBarActivity implements RunningAppFragment.OnRunningAppRefreshListener{

To ensure that the Activity implements this interface, we can forcibly convert the Activity to this interface object during onAttach, as shown below:
public void onAttach(Activity activity){super.onAttach(activity);try{onRunningAppRefreshListener = (OnRunningAppRefreshListener) activity;}catch(ClassCastException e){throw new ClassCastException(activity.toString()+ " must implement OnRunningAppRefreshListener");}}

In this way, if the Activity does not implement this interface, an exception will be thrown.
End. Click to download the source code!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.