Cyclerotationview: Carousel Diagram of custom controls

Source: Internet
Author: User
Tags blank page

Cyclerotationview: Custom control, the main function is to implement similar with the various mall home page ad carousel. In fact, like this more common custom control is already full street, although said "do not reinvent the wheel", but does not mean that do not care about the wheel is how to create, the spirit of "know it is the reason why" the attitude, completed the control (can not be used to learn it). The usual, first (no article is bullying):

For the rotation of the picture switch, we immediately think of viewpager this control, because it already has left and right sliding function, used to implement the Carousel diagram effect is simple, this article is based on the implementation of Viewpager this control, divided it into the following four parts:
1. Picture Carousel
2. Indicator
3, Picture indicator linkage
4. Timed Carousel
The following starts to implement (a bit verbose, do not spray ...) :

Photo Carousel Layout File
<RelativelayoutAndroid:layout_width="Match_parent"android:layout_height="120DP" ><Android.support.v4.view.ViewPagerAndroid:id="@+id/viewpager"Android:layout_width="Match_parent"android:layout_height="120DP"/><LinearLayoutAndroid:layout_width="Match_parent"android:layout_height="18DP"Android:layout_alignparentbottom="True"Android:background="#66000000"android:orientation="Horizontal" ><TextViewAndroid:id="@+id/title"Android:layout_width="0DP"android:layout_height="Wrap_content"android:layout_marginleft="15DP"android:layout_weight="1"android:textcolor= "#FFFFFF"/> <linearlayout android:id="@+id/pointgroup"  Android:layout_width= "wrap_content" android:layout_height="wrap_content" android:layout_gravity ="center" android:layout_marginright="15DP" android:orientation="Horizontal"/>  </linearlayout> </relativelayout>        

First look at the layout file, the outermost relativelayout represents the entire control, contains Viewpager and a linearlayout, and TextView and LinearLayout are included in LinearLayout. Here's a note: The first LinearLayout contains the title (Id=title) and the indicator (Id=pointgroup), the second linearlayout is used to wrap the indicator (done in the code), to give an understanding of the diagram (here I do not set the title):

Code implementation
    /**     * 初始化布局     * @param mContext     */    private void initView(Context mContext) { View view = LayoutInflater.from(mContext) .inflate(R.layout.cycle_rotation_layout, this, true); mViewPager = (ViewPager) view.findViewById(R.id.viewPager); mPointGroup = (LinearLayout)view.findViewById(R.id.pointGroup); }

The first is to load the layout file just now, Viewpager and Pointgroup to find out;

    for (int i = 0; i < images.length; i++) { // 创建 ImageView,并设置图片 ImageView img = new ImageView(mContext); // 把图片扩大到 ImageView 的大小 img.setScaleType(ImageView.ScaleType.FIT_XY); img.setImageResource(images[i]); mList.add(img); }

Based on the number of images passed by the user to traverse the creation of the corresponding number of ImageView, and then set the image to create the ImageView, and then use a List set to install ImageView to use. In the scene of Fragement + Viewpager + tablayout The Viewpager is filled with fragement, and here the Viewpager is filled with ImageView;

    /** * Adapter * */class Cycleadapter extends Pageradapter {@OverridePublicIntGetCount () {return integer.max_value; }@OverridePublic ObjectInstantiateitem (ViewGroup container,int position) {position = position% mlist.size (); //Determine if the item already has the parent final View child = mlist.get (position); if (child.getparent () = null) {Container.removeview (child);} Container.addview (Mlist.get (position)); return Mlist.get (position);} @Override public void destroyitem (ViewGroup container, int position, Object object) {} @ Override Public boolean isviewfromobject (View view, Object object) { return view = = Object;}} 

The adapter is on, and returning Integer.max_value in the GetCount () method is because Viewpager does not loop, giving such a value (it is said that the Integer.max_value is 1 billion, and I have not tried it) to keep it sliding down. The question is: will there be a performance problem with such a large number? I am also curious to see who is more interested.
Also say the Instantiateitem () method, why do you want to determine the state of the parent? The reason for this is that if you do not, you will get an error when swiping left Viewpager: The specified child already has a parent. You must call Removeview .
Note:Instantiateitem () is judged, Destroyitem () no longer removeview (), otherwise a blank page appears.

Indicator
    /** * Create indicator */Forint i =0; i < images.length; i + +) {//Create indicator, essentially also ImageView ImageView point = new ImageView (Mcontext); Point.setimageresource (r.drawable.shape_ Point_selector); //Indicator layout parameters linearlayout.layoutparams params = new Linearlayout.layoutparams (pointsize, pointsize); //2nd set the left margin if (i > 0) {params.leftmargin = Pointmargin; point.setselected (false); //1th} selected by default else {point.setselected (true); //1th} point.setlayoutparams (params) is selected by default; //Set the parameter Mpointgroup.addview (point) for the indicator; //Add indicator to container}             

The indicator is created to correspond to the number of ImageView, so the number of images set by the user is also traversed. The following is the relevant layout file for the indicator:
Shape_point_selector:

<selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:state_selected="true" android:drawable="@drawable/shape_point_selected" /> <item android:state_selected="false" android:drawable="@drawable/shape_point_normal" /></selector>

Shape_point_selected:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <solid android:color="#FFFFFF"/></shape>

Shape_point_normal:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <solid android:color="#66000000"/></shape>

Both Viewpager and Pointgroup were created, followed by their linkage:

Linkage
Mviewpager.setadapter (New Cycleadapter ());Viewpager's Listener Event Mviewpager.addonpagechangelistener (New Viewpager.onpagechangelistener () {@OverridePublicvoidOnpagescrolled (int position,float positionoffset, int positionoffsetpixels) {} int lastposition; @Override public void onpageselected (int position) {position = position% mlist.size (); //Set Current dot check mpointgroup.getchildat (position). setselected (true); //Set the previous dot unchecked Mpointgroup.getchildat (lastposition). setselected (false); lastposition = position;} @Override public void onpagescrollstatechanged (int.) {}});     

Add a listener event to Viewpager, and the corresponding position indicator is selected when a page is selected. Position% mlist.size (): Adapter Returns a very large value in GetCount (), where redundancy guarantees that null pointer exceptions are not present.

Timed Carousel
Mhandler.postdelayed (New Runnable () { @Override public void Run () { //the currently selected item int current Item = Mviewpager.getcurrentitem (); //Determine if it is the last item if (CurrentItem = = Mviewpager.getadapter (). GetCount ()- 1) {Mviewpager.setcurrentitem ( C10>1); } else {mviewpager.setcurrentitem (CurrentItem + 1);} //Send yourself a message mhandler.postdelayed (this, ( );}}, + );      

Timing Carousel is also very simple, with Handler to delay to send their own messages. When the Viewpager slides to the last one, it sets the Mviewpager.setcurrentitem (1) to implement the cyclic carousel.
The basic carousel function is completed here, but there are many expansion functions, such as click events, user settings Image link, these I have already realized, here is not introduced, interested can see the source: cyclerotation

Cyclerotationview: Carousel Diagram of custom controls

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.