Background
The effect of a carousel chart is to be done recently. Read several articles on the Internet. Basically can find the implementation, the effect is quite good, but in writing when the feeling every time to go alone and once again in the activity to write a bunch of code. So I encapsulated a bit. This is just the next package that is packaged into a control that does not have to be repeated every time you write code.
Implementation analysis
The function of the carousel is to realize left and right sliding ads, picture information display, then we use Viewpager to achieve, because of the user experience, we also need to add an indicator to slide to the first number of Carousel map. Indicator we are able to use a linear layout to display the view according to the carousel diagram that we want to show, we do this kind of control has no special effect, in fact, is a combination of two controls, only 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 our own definition of the control to implement.
Start Here
1. Define a control to inherit Framelayout, write an XML file
Public class carouselview extends framelayout implements Viewpager . Onpagechangelistener { PrivateContext context;Private intTotalCount = -;//Total. This is for infinite sliding settings. Private intShowcount;//Number of carousel graphs to display Private intCurrentPosition =0;//Current location of Viewpager PrivateViewpager Viewpager;PrivateLinearLayout carousellayout;//layout of the display indicator PrivateAdapter Adapter;Private intPageitemwidth;//width of each indicator Private Booleanisusertouched =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,intDEFSTYLEATTR) {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.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 includes two of the controls Viewpager and Carousellayout are included in the defined Carouselview. Here's how 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);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 method that is often used in its own definition of a control, which indicates that the component is loaded from XML. In this method we get the Viewpager object and the Carousellayout object through the Layoutinflater.from (context). Inflate and assign a value to Pageitemwidth.
Set Addonpagechangelistener for Viewpager at the same time. Don't forget to call addview here, otherwise the control will not show!
3. Get the data by setting the Set method. Initialize the interface effect at the same time
In this step we have obtained the Viewpager object for the display carousel. Then let it show that you must have thought of writing a class inheritance pageradapter. Then rewrite the Getcount,isviewfromobject,isviewfromobject,destroyitem and other methods to let Viewpager display the carousel diagram. But we can't write too fixed. Since it is possible for each person to display different data, we define an interface to write our own logic to those who use it externally. On the code:
//定义一个接口让外部设置展示的Viewpublicinterface Adapter{ boolean isEmpty(); View getView(int position); int getCount(); }
Adapter for//viewpager class viewpageradapter extends pageradapter {@Override Public intGetCount () {returnTotalCount; } @Override Public BooleanIsviewfromobject (View view, Object object) {returnView==object; } @Override PublicObject Isviewfromobject (ViewGroupContainer,intPosition) {position%= showcount;//The GetView () of the calling interface gets the view that the user wants to display;View view = Adapter.getview (position);Container. AddView (view);returnView } @Override Public voidDestroyitem (ViewGroupContainer,intPosition, Object object) {Container. Removeview ((View) object); } @Override Public intGetItemPosition (Object object) {return Super. GetItemPosition (object); } @Override Public voidFinishupdate (ViewGroupContainer) {Super. Finishupdate (Container);intPosition = Viewpager.getcurrentitem ();//implementation of 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 direction and slidePosition = Showcount-1; Viewpager.setcurrentitem (Position,false); } } }
//为外部提供设置数据源的方法,同一时候为ViewPager做展示publicvoidsetAdapter(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, initialize the interface effect at the same time, the Init () method is the initialization of the data, code such as the following:
Private void Init() {Viewpager.setadapter (NULL); Carousellayout.removeallviews ();//Clear the previous data if(Adapter.isempty ()) {return; }intCount = Adapter.getcount (); Showcount = Adapter.getcount (); for(intI=0; i<count;i++) {View view =NewView (context);//view to make indicator, show effect through state if(currentposition==i) {view.setpressed (true); Linearlayout.layoutparamsparams=NewLinearlayout.layoutparams (Pageitemwidth + convertutils.dip2px (context,3), Pageitemwidth + convertutils.dip2px (context,3));params. SetMargins (Pageitemwidth,0,0,0); View.setlayoutparams (params); }Else{Linearlayout.layoutparamsparams=NewLinearlayout.layoutparams (Pageitemwidth,pageitemwidth);params. SetMargins (Pageitemwidth,0,0,0); View.setlayoutparams (params); } view.setbackgroundresource (R.drawable.carousel_layout_page); Carousellayout.addview (view); } viewpager.setadapter (NewViewpageradapter ()); Viewpager.setcurrentitem (0);//Let your finger touch the active carousel This. Viewpager.setontouchlistener (NewOntouchlistener () {@Override PublicBooleanOnTouch(View V, motioneventEvent) {Switch(Event. Getaction ()) { CaseMotionevent.action_down: CaseMotionEvent.ACTION_MOVE:isUserTouched =true; Break; CaseMotionEvent.ACTION_UP:isUserTouched =false; Break; }return false; } }); Mtimer.schedule (Mtimertask, the, the); }
This is the basic logic code. The control for a carousel diagram is ready.
Take a look down and use:
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>
Gets the control in Java code. Set the interface at the same time
Carouselview Carouselview = (carouselview) Findviewbyid (R.id.carouselview); Carouselview.setadapter (NewCarouselview.adapter () {@Override Public Boolean IsEmpty() {return false; }@Override PublicViewGetView(intPosition) {View view = Minflater.inflate (R.layout.item,NULL); ImageView ImageView = (ImageView) View.findviewbyid (r.id.image); Imageview.setimageresource (Mimagessrc[position]);returnView }@Override Public int GetCount() {returnMimagessrc.length; } });
Returns whether it is empty. in GetView (int position), return the view that we want to return, it is so simple.
If it's helpful to you. Remember to give praise to the comments yo!
source code Download please poke --"Picture carousel
Android self-defining a control's Carousel chart control