Slideshow widget of Android custom control and android custom control

Source: Internet
Author: User

Slideshow widget of Android custom control and android custom control
Background

I recently want to create a carousel image. After reading several articles online, I can basically find the implementation, and the results are quite good, but at the time of writing, I felt that I had to write a bunch of code in the Activity every time. So I encapsulated it myself. The original source of the implementation principle of this carousel diagram is the implementation of the cyclic ad space component, which is encapsulated as a control and does not need to be repeatedly written every time.

Implementation Analysis

The slideshow function is to display advertisements and Image Information sliding between the left and right sides. ViewPager is used for this purpose. Considering the user experience, we also need to add an indicator below to indicate the number of slideshow slides. We can use a linear layout to set the display View based on the carousel chart to be displayed. We have to make such a control with no special effect. It is actually a combination of two controls, we only need to handle the interaction between them internally (in fact, it is the display of the following indicator when ViewPager is rolling), so we will implement it using the combination of custom controls.
Start

1. Define a control to inherit FrameLayout and write an xml file
Public class extends uselview extends FrameLayout implements ViewPager. onPageChangeListener {private Context context; private int totalCount = 100; // The total number, which is the private int showCount set for unlimited sliding; // The number of carousel images to be displayed: private int currentPosition = 0; // the position of the current ViewPager: private ViewPager viewPager; private LinearLayout: usellayout; // the layout of the Display Indicator: private Adapter adapter; private int pageItemWidth; // The width of each indicator private boolean isUserTouched = false; public writable uselview (Context context) {super (context); this. context = context;} public extends uselview (Context context, AttributeSet attrs) {super (context, attrs); this. context = context;} public incluuselview (Context context, AttributeSet attrs, int defStyleAttr) {super (context, attrs, defStyleAttr); this. context = context ;}
<?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">    <android.support.v4.view.ViewPager        android:id="@+id/gallery"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:unselectedAlpha="1">    </android.support.v4.view.ViewPager>    <LinearLayout android:layout_height="wrap_content"        android:layout_width="fill_parent"        android:orientation="horizontal"        android:gravity="center"        android:layout_gravity="center|bottom"        android:id="@+id/CarouselLayoutPage"        android:padding="10dip">    </LinearLayout></FrameLayout>

The code above contains the ViewPager and carouselLayout controls to be used in the defined CarouselView.

2. obtain the required controls in onFinishInflate ().
@Override    protected void onFinishInflate() {        super.onFinishInflate();        View view = LayoutInflater.from(context).inflate(R.layout.carousel_layout,null);        this.viewPager = (ViewPager) view.findViewById(R.id.gallery);        this.carouselLayout = (LinearLayout)view.findViewById(R.id.CarouselLayoutPage);        pageItemWidth = ConvertUtils.dip2px(context,5);        this.viewPager.addOnPageChangeListener(this);        addView(view);    }

The onFinishInflate () method is a commonly used method in custom controls. It indicates that the component is loaded from XML. In this method, LayoutInflater is used. from (context ). inflate obtains ViewPager and carouselLayout objects, and assigns values to pageItemWidth.
Set addOnPageChangeListener for viewPager. Do not forget to call addView () here; otherwise the control will not be displayed!

3. set the set method to obtain data and initialize the interface effect.

In this step, we have obtained the ViewPager object for displaying the carousel image. Next we want to show it. You must think of writing a class to inherit PagerAdapter, and then rewrite getCount, isViewFromObject, isViewFromObject, destroyItem and other methods for ViewPager to display carousel images. However, we cannot write it too fixed, because each person may want to display different data, so we define an interface for external users to write their own logic. Code:

// Define an interface for external display of Viewpublic interface Adapter {boolean isEmpty (); View getView (int position); int getCount ();}
// ViewPager adapter class ViewPagerAdapter extends PagerAdapter {@ Override public int getCount () {return totalCount ;}@ Override public boolean isViewFromObject (View view, Object object) {return view = object ;}@ Override public Object isViewFromObject (ViewGroup container, int position) {position % = showCount; // call the getView () API () obtains the View to be displayed by the user. View view = adapter. getView (position); container. addView (view); return view;} @ Override public void destroyItem (ViewGroup container, int position, Object object Object) {container. removeView (View) object);} @ Override public int getItemPosition (Object object) {return super. getItemPosition (object) ;}@ Override public void finishUpdate (ViewGroup container) {super. finishUpdate (container); int position = viewPager. getCurrentItem (); // The implementation of Viewpager to the first page can move to the left if (position = 0) {position = showCount; viewPager. setCurrentItem (position, false);} else if (position = totalCount-1) {// The implementation of ViewPager to the last page slides position = showCount-1; viewPager. setCurrentItem (position, false );}}}
// Provides external methods for setting data sources, and displays public void setAdapter (Adapter adapter) {this. adapter = adapter; if (adapter! = Null) {init ();}}

The above Code defines an interface for external users to set data, provides setAdapter to assign values to the adapter, and initializes the interface effect. The init () method is the data initialization. The Code is as follows:

Private void init () {viewPager. setAdapter (null); extends usellayout. removeAllViews (); // clear the previous data if (adapter. isEmpty () {return;} int count = adapter. getCount (); showCount = adapter. getCount (); for (int I = 0; I <count; I ++) {View view = new View (context); // View used for indicator, use state to demonstrate the effect if (currentPosition = I) {view. setPressed (true); LinearLayout. layoutParams params = new LinearLayout. layoutParams (pageItemWidth + ConvertUtils. dip2px (context, 3), pageItemWidth + ConvertUtils. dip2px (context, 3); params. setMargins (pageItemWidth, 0, 0, 0); view. setLayoutParams (params);} else {LinearLayout. layoutParams params = new LinearLayout. layoutParams (pageItemWidth, pageItemWidth); params. setMargins (pageItemWidth, 0, 0); view. setLayoutParams (params);} view. setBackgroundResource (R. drawable. carousel_layout_page); carouselLayout. addView (view);} viewPager. setAdapter (new ViewPagerAdapter (); viewPager. setCurrentItem (0); // automatic carousel fails when the finger is touched. viewPager. setOnTouchListener (new OnTouchListener () {@ Override public boolean onTouch (View v, MotionEvent event) {switch (event. getAction () {case MotionEvent. ACTION_DOWN: case MotionEvent. ACTION_MOVE: isUserTouched = true; break; case MotionEvent. ACTION_UP: isUserTouched = false; break;} return false ;}}); mTimer. schedule (mTimerTask, 3000,300 0 );}

The main logic code is like this. A carousel chart control is ready. Let's take a look at the usage:

4. Use

Write our carousel chart control in xml:

 <com.yangqiangyu.test.carouselview.CarouselView        android:layout_width="match_parent"        android:layout_height="220dp"> </com.yangqiangyu.test.carouselview.CarouselView>

Get the control in java code and set the interface

 CarouselView carouselView = (CarouselView) findViewById(R.id.CarouselView);        carouselView.setAdapter(new CarouselView.Adapter() {            @Override            public boolean isEmpty() {                return false;            }            @Override            public View getView(int position) {                View view = mInflater.inflate(R.layout.item,null);                ImageView imageView = (ImageView) view.findViewById(R.id.image);                imageView.setImageResource(mImagesSrc[position]);                return view;            }            @Override            public int getCount() {                return mImagesSrc.length;            }        });

Whether the return value is null. In getView (int position), return the View we want to return, which is so simple.

If it is helpful to you, remember to give likes a comment!

Source code download request stamp-- Image carousel

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: info-contact@alibabacloud.com 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.