The Carousel Chart control for Android custom controls

Source: Internet
Author: User

Background

Recently to do a round-the-map effect, read a few articles on the Internet, basically can find the implementation, the effect is quite good, but in writing feel each time to go back to the activity to write a bunch of code. So I encapsulated a bit. The principle of the implementation of the Carousel diagram is the source: the implementation of the loop ad bit component, here just do the next package into a control, do not have to write code every time.

Implementation analysis

The function of the carousel is to realize left and right sliding advertisement, picture information display, then we use Viewpager to realize, due to the user experience, we also need to add an indicator below to slide to the number of Carousel diagram. Indicator we can use a linear layout to display the view according to the Carousel diagram to be shown, we have to do such a control does not have any special effect, is actually two control of the combination, but we have to internally handle the interaction between them (in fact, when the Viewpager scrolling, Display of the following indicators), so we use the combination of custom controls to implement.
Start Here

1. Define a control to inherit Framelayout, write an XML file
PublicClassCarouselviewExtendsFramelayoutImplementsViewpager.Onpagechangelistener {Private context context;Privateint totalcount =100;Total, which is for infinite sliding settingsPrivateint showcount;Number of carousel graphs to displayPrivateint currentposition =0;Location of current ViewpagerPrivate Viewpager Viewpager;Private LinearLayout carousellayout;Layout of the display indicatorPrivate Adapter Adapter;Privateint pageitemwidth;//width of each indicator private boolean isusertouched = FALSE; public carouselview (context context) { super (context); this.context = Context;} public carouselview (context context, AttributeSet attrs) {super (context, attrs); this.context = Context;} public carouselview (context context, AttributeSet attrs, int defstyleattr) {super (context, attrs, defstyleattr); this.context = context; } 
<?xml version= "1.0" encoding= "Utf-8"?><FramelayoutXmlns:android="Http://schemas.android.com/apk/res/android"Android:layout_width="Match_parent"android:layout_height="Match_parent" ><Android.support.v4.view.ViewPagerAndroid: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 above code contains two of the controls Viewpager and Carousellayout are included in the defined Carouselview, the following is to get

2. Get the controls we need in Onfinishinflate ()
@Override protected void Onfinishinflate () {Super. Onfinishinflate (); View view = Layoutinflater. from (context). Inflate (R. layout.carousel_layout,null) .viewpager = (viewpager) view.findviewbyid (R.id.gallery) .carousellayout = (linearlayout) view.findviewbyid (R.id5) .addonpagechangelistener (this)             

The Onfinishinflate () method is a common method in a custom control that represents the completion of a component from an XML load, in which we pass layoutinflater.from (context). Inflate Gets the Viewpager object and the Carousellayout object, and assigns a value to the pageitemwidth.
Set Addonpagechangelistener for Viewpager at the same time. Don't forget to call addview here, otherwise the control will not show!

3, by setting the Set method to get the data, while initializing the interface effect

At this point we've got the Viewpager object that shows the carousel, and then let it show that you're definitely thinking of writing a class to inherit Pageradapter, and then rewrite Getcount,isviewfromobject,isviewfromobject, Destroyitem and other methods to let Viewpager show the Carousel diagram. But we can't write it too fixed, because maybe everyone wants to show different data, so we define an interface to write our own logic to people who use it externally. On the code:

//定义一个接口让外部设置展示的Viewpublic interface Adapter{        boolean isEmpty();        View getView(int position);        int getCount(); }
Adapter for ViewpagerClassViewpageradapterExtendsPageradapter {@OverridePublicint GetCount () {return totalcount; } @OverridePublicBoolean Isviewfromobject (View view, Object object) {return view==object; } @OverridePublic Object Isviewfromobject (viewgroupContainerint position) {position%= showcount;The GetView () of the calling interface gets the view the user wants to display; View view = Adapter.getview (position);Container.addview (view);return view; } @OverridePublicvoid Destroyitem (ViewGroupContainerint position, Object object) {Container.removeview ((View) object); } @OverridePublicint GetItemPosition (Object object) {Returnsuper.getitemposition (object);} @Override public void finishupdate (viewgroup container) {super.finishupdate (container); Span class= "Hljs-keyword" >int position = Viewpager.getcurrentitem (); //implementation Viewpager to the first page slide to the left if (position== 0) {position=showcount; Viewpager.setcurrentitem (Position,false);} else if (Position==totalcount-1) {//viewpager to the last page of the implementation toward and sliding position = showcount-1; Viewpager.setcurrentitem (Position,false);}} } 
//为外部提供设置数据源的方法,同时为ViewPager做展示public void setAdapter(Adapter adapter){        this.adapter = adapter; if (adapter!=null){ init(); } }

The code above is to define an interface to set the data externally, provide setadapter to assign values to adapter, and initialize the interface effect, the init () method is the initialization of the data, the code is as follows:

PrivatevoidInit () {Viewpager.setadapter (NULL); Carousellayout.removeallviews ();Clear the previous dataif (Adapter.isempty ()) {Return }int count = Adapter.getcount (); Showcount = Adapter.getcount ();for (int i=0;i<count;i++) {View view =New View (context);A view that is used to make an indicator, which is displayed through state.if (currentposition==i) {view.setpressed (true); Linearlayout.layoutparamsparams =New Linearlayout.layoutparams (Pageitemwidth + convertutils.dip2px (context,3), Pageitemwidth + convertutils.dip2px (context,3));Params.setmargins (Pageitemwidth,0,0,0); View.setlayoutparams (params); }else {Linearlayout.layoutparamsparams =New Linearlayout.layoutparams (Pageitemwidth,pageitemwidth);Params.setmargins (Pageitemwidth,0,0,0); View.setlayoutparams (params); } view.setbackgroundresource (R.drawable.carousel_layout_page); Carousellayout.addview (view); } viewpager.setadapter (New Viewpageradapter ()); Viewpager.setcurrentitem (0);Automatic rotation does not work when your finger touchesthis.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, 3000);}    

The main logic code is this, the control of a carousel diagram is done. Here's a look at using:

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;}});     

Returns whether it is empty, in GetView (int position) Return the view that we want to return, it is so simple.

For your help, remember to give praise to the comments yo!

source Download Please poke --"Picture carousel

The Carousel Chart control for Android 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.