Android custom control implements a simple carousel graph control _android

Source: Internet
Author: User
Tags object object

Recently to do a carousel map effect, read several articles on the internet, basically can find the implementation, the effect is quite good, but in writing feel each time to be alone in the activity to write a bunch of code. So I encapsulated a bit. The principle of the implementation of the Carousel map Source: The implementation of the circular advertising bit components, here just do the next package into a control, do not have to write code every time.

Effect Chart:

Implementation analysis
The function of the carousel diagram is to realize the advertising, picture information display, then we use Viewpager to realize, because considering the user experience, we also need to add an indicator below to mark the slide to the first few of the Carousel map. Indicator we can use a linear layout to set the view that is displayed according to the carousel map to display, there's no special effect to having a control like this, but it's a combination of two controls, but we're going to have to deal with the interaction between them internally (in fact, Viewpager scrolling, The display of the indicator below), so we use a combination of custom controls to implement it.
Here we go.

1, define a control to inherit Framelayout, write an XML file

public class Carouselview extends Framelayout implements Viewpager.onpagechangelistener {private context context; private int TotalCount =100;//Total, this is a private int showcount;//for unlimited sliding settings to display the number of carousel graphs private int currentposition =0;//current

  Viewpager's position private Viewpager viewpager;
  Private LinearLayout carousellayout;//Display indicator layout private Adapter Adapter;

  private int pageitemwidth;//The width of each indicator private Boolean isusertouched = false;
    Public Carouselview {Super (context);
  This.context = context;
    Public Carouselview (context, AttributeSet attrs) {Super (context, attrs);
  This.context = context; 
    Public Carouselview (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_paren T "android:layout_height=" Match_parent "android:unselectedalpha=" 1 "> &LT;/ANDROID.SUPPORT.V4.VIEW.VIEWPAGER&G
  T <linearlayout android:layout_height= "wrap_content" android:layout_width= fill_parent "android:orientation=" hor
    Izontal "android:gravity=" center "android:layout_gravity=" Center|bottom "android:id=" @+id/carousellayoutpage "

 android:padding= "10dip" > </LinearLayout> </FrameLayout>

The code above contains two of the controls that are to be used Viewpager and Carousellayout are included in the defined Carouselview, and the following is to obtain

2, Onfinishinflate () to get the control we need

@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 that represents the completion of a component from an XML load, in which we pass the Layoutinflater.from (context). Inflate Gets the Viewpager object and the Carousellayout object, and assigns the pageitemwidth.
Also set Addonpagechangelistener for Viewpager. Don't forget to call AddView () here, otherwise the control will not show!

3, by setting the Set method to obtain data, while initializing the interface effect
At this point we've got the Viewpager object that shows the carousel map, and then let it show that you must have thought of writing a class to inherit Pageradapter, and then rewrite Getcount,isviewfromobject,isviewfromobject, Destroyitem and other methods to let Viewpager show the Carousel map. But we can't write too fixed, because maybe everyone wants to show different data, so we define an interface to write our own logic to the people who use it externally. Code on:

Define an interface to let the external settings show the View public interface adapter{Boolean isempty ();
    View GetView (int position);
  int GetCount (); Adapter class Viewpageradapter extends Pageradapter {@Override public int getcount ()//viewpager
    Talcount;
    @Override public boolean isviewfromobject (view view, Object object) {return view==object;
      @Override public Object isviewfromobject (viewgroup container, int position) {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);
    return view; @Override public void Destroyitem (ViewGroup container, int position, object object) {Container.removevie
    W (View) object;
    @Override public int GetItemPosition (object) {return Super.getitemposition (object);

      @Override public void Finishupdate (ViewGroup container) {super.finishupdate (container); Int Position = Viewpager.getcurrentitem ();
        Implementation of Viewpager to the first page can slide to the left if (position==0) {position=showcount;

      Viewpager.setcurrentitem (Position,false);
        The implementation of}else if (position==totalcount-1) {//viewpager to the last page is sliding position = showCount-1;
      Viewpager.setcurrentitem (Position,false);
    Provide an external method for setting up the data source, and display the public void Setadapter (Adapter Adapter) {this.adapter = Adapter for Viewpager).
    if (adapter!=null) {init ();

 }
  }

The code above defines an interface for setting data externally, providing setadapter to assign values to adapter, and initializing interface effects, the init () method is the initialization of the data as follows:

private void Init () {viewpager.setadapter (null);
    Carousellayout.removeallviews ();//clear before the data if (Adapter.isempty ()) {return;
    int count = Adapter.getcount ();
    Showcount = Adapter.getcount ();
      for (int i=0;i<count;i++) {View view = new view (context);
        The view that is used to make the indicator, by state to show 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,0);
      View.setlayoutparams (params);
      } view.setbackgroundresource (R.drawable.carousel_layout_page);
    Carousellayout.addview (view); } viewpager.setadapter (New VIEWPAgeradapter ());

    Viewpager.setcurrentitem (0); When the finger touches, the automatic wheel is not valid This.viewPager.setOnTouchListener (new Ontouchlistener () {@Override public boolean OnTo Uch (View V, motionevent event) {switch (event.getaction ()) {case MotionEvent.ACTION_DOWN:cas
            e MotionEvent.ACTION_MOVE:isUserTouched = true;
          Break
            Case MotionEvent.ACTION_UP:isUserTouched = false;
        Break
      return false;
    }
    });
  Mtimer.schedule (Mtimertask, 3000, 3000);

 }

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

4. Use
Write our wheel map 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 and sets 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, return in GetView (int position) we want to return to the view, it is so simple.

I hope this article will help you learn about Android software programming.

Related Article

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.