English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
First, let's take a look at an effect diagram:
When it comes to implementing the carousel effect of ViewPager, PagerAdapter will definitely be used. Let's first introduce this class.
Introduction to PagerAdapter
PagerAdapter is Android.support.v4The classes in the package are an abstract class, directly inheriting from Object, and importing package android.support.v4.view.PagerAdapter can be used.
PagerAdapter is the adapter of viewPager, and viewPager is also in android.support.v4A powerful control added in the extended package, which can realize the sliding effect of the control, such as the sliding effect of the advertisement bar commonly seen in our software, which can be realized by viewPager. Today, we mainly introduce how to use viewPager and override PagerAdapter to realize the sliding effect of the common advertisement bar.
Since it is an abstract class, we create a new class to inherit it and override four methods:
1.public Object instantiateItem(ViewGroup container, int position)
2.public void destroyItem(ViewGroup container, int position, Object object)
3.public int getCount()
4.public boolean isViewFromObject(View arg0, Object arg1)
MyViewPagerAdapter class:
public class MyViewPagerAdapter extends PagerAdapter { private List<ImageView> mList; public MyViewPagerAdapter(List<ImageView> mList){ this.mList=mList; } //When the image to be displayed is cached, this method will be called to initialize the image display //We add the ImageView we want to display to the ViewGroup public Object instantiateItem(ViewGroup container, int position) { // TODO Auto-generated method stub container.addView(mList.get(position)); return mList.get(position); } @Override //PagerAdapter caches only three images to be displayed, if the sliding image exceeds the cache range, this method will be called to destroy the image public void destroyItem(ViewGroup container, int position, Object object) { // TODO Auto-generated method stub container.removeView(mList.get(position)); } //Get the number of controls to be scrolled public int getCount() { // TODO Auto-generated method stub return mList.size(); } //to determine whether the same photo is displayed, we will compare the two images and then return public boolean isViewFromObject(View arg0, Object arg1) { // TODO Auto-generated method stub return arg0==arg1; } }
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <android.support.v4.view.ViewPager android:id="@"+id/vp" android:layout_width="match_parent" android:layout_height="200dp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignBottom="@id/vp" android:background="#33000000" android:orientation="vertical" android:paddingBottom="10dp" > <LinearLayout android:id="@"+id/ll_points" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:orientation="horizontal" android:paddingBottom="10dp" > </LinearLayout> </LinearLayout> </RelativeLayout>
MainActivity:
public class MainActivity extends Activity { private ViewPager mVp; //private TextView tvTitle; private LinearLayout llPoints; //private String[] titles;// Store all the titles to be displayed private int[] images;// Store all the image resource IDs to be displayed private List<ImageView> list = new ArrayList<ImageView>();;// Store all ImageView objects to be displayed in the ViewPager object private int prevPosition = 0; private Handler handler = new Handler() { @SuppressLint("HandlerLeak") public void handleMessage(android.os.Message msg) { switch (msg.what) { case 0: // Get the index of the current page of mvp int currentItem = mVp.getCurrentItem(); // The index of the next page to be displayed currentItem++; // Set the page displayed by ViewPager mVp.setCurrentItem(currentItem % list.size()); break; default: break; } }; }; @SuppressWarnings("deprecation") protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); // titles = getTitles(); images = getImages(); for (int i = 0; i < images.length; i++) { ImageView iv = new ImageView(this); iv.setBackgroundResource(images[i]); list.add(iv); //Generate the corresponding number of small dots according to the number of images final View view = new View(this); view.setBackgroundResource(R.drawable.login__05); DisplayMetrics metrics = new DisplayMetrics(); float width=TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX,30, metrics); float height=TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 30, metrics); LinearLayout.LayoutParams params=new LinearLayout.LayoutParams((int)width,(int)height); params.leftMargin=5; view.setLayoutParams(params); llPoints.addView(view); } //Set the title displayed on the first page //tvTitle.setText(titles[0]); //Set the background image of the small dot when the first page is set llPoints.getChildAt(0).setBackgroundResource(R.drawable.login__03); //The following encapsulates the ViewPager adapter MyViewPagerAdapter adapter=new MyViewPagerAdapter(list); mVp.setAdapter(adapter); //Set the listener for page changes of the ViewPager object mVp.setOnPageChangeListener(new OnPageChangeListener() { @Override //When the next page is selected public void onPageSelected(int arg0) { // TODO Auto-generated method stub //tvTitle.setText(titles[arg0%list.size()]); llPoints.getChildAt(prevPosition).setBackgroundResource(R.drawable.login__05); llPoints.getChildAt(arg0).setBackgroundResource(R.drawable.login__03); //Set the current point position as the previous point position for the next change prevPosition=arg0; } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { // TODO Auto-generated method stub } @Override public void onPageScrollStateChanged(int arg0) { // TODO Auto-generated method stub } }); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub while (true) { SystemClock.sleep(3000); handler.sendEmptyMessage(0); } } }).start(); } private void initView() { // TODO Auto-generated method stub mVp = (ViewPager) findViewById(R.id.vp); //tvTitle = (TextView) findViewById(R.id.tv_title); llPoints = (LinearLayout) findViewById(R.id.ll_points); } private int[] getImages(){ return new int[]{R.drawable.banner_01,R.drawable.banner_02,R.drawable.banner_03}; } }
That's all for this article. I hope it will be helpful to everyone's learning and that everyone will support the Yelling Tutorial more.
Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please send an email to codebox.com (replace # with @ when sending email) to report violations, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.