Android enables ad rotation via Viewflipper and can be toggled via gesture swipe

Source: Internet
Author: User

In order to realize the advertisement carousel function, looked for many methods on the net, some effect is very good, but the code is too troublesome, and mostly uses the Viewpager, in short is not very satisfied.

So I looked at the SDK has a control is viewflipper, use more convenient, so tried, and finally achieved the desired effect. Share with you here.

First look at the effect (mainly the layout of the effect, after all, gesture recognition and slippage is not very good display, lazy to make GIF):

1. layout file. xml

<linearlayout android:layout_width= "fill_parent" android:layout_height= "fill_parent" android:orientation= "vert ical "xmlns:android=" http://schemas.android.com/apk/res/android "> <viewflipper Android:layout_widt H= "Fill_parent" android:layout_height= "120DP" android:id= "@+id/details" > </viewflipp   er> <relativelayout android:layout_width= "fill_parent" android:layout_height= "16DP" > <linearlayout android:layout_width= "fill_parent" android:layout_height= "16DP" android:orientation= "ho Rizontal "android:gravity=" right "> <view android:id=" @+id/v_dot0 "St yle= "@style/dot_style" android:background= "@drawable/dot_focused"/> <view android:id = "@+id/v_dot1" style= "@style/dot_style"/> <view android:id= "@+id/v_dot2" style= "@st Yle/dot_style "/&Gt </LinearLayout> <textview android:id= "@+id/title" android:layout_width= "Wrap_content" Androi d:layout_height= "Wrap_content" android:gravity= "left" android:text= "Hello"/> </r Elativelayout> </LinearLayout>

Let me explain the layout.

First, the outermost layer is a linearlayout layout to fill the entire screen.

The second layer is the control viewflipper and Relativelayout. Where Viewflipper is the implementation of the picture Carousel, Relationlayout is the information below the picture, the title of the film (&&) and the position of the picture in all pictures (the white dots of the rightmost form)

The third layer is actually the second layer of the relativelayout to expand, there is a TextView control to display the title, and three view control to display the dots.

Here are some of the style and drawable code to use (this part of the code comes from the network):

Top 5 placed under the Res/drawable folder

1, Btn_back_selector.xml

<?xml version= "1.0" encoding= "Utf-8"? ><selector xmlns:android= "http://schemas.android.com/apk/res/ Android ">    <item android:drawable=" @drawable/btn_top_pressed "android:state_focused=" true "></item >    <item android:drawable= "@drawable/btn_top_pressed" android:state_pressed= "true" ></item>    <item android:drawable= "@drawable/btn_top_pressed" android:state_selected= "true" ></item>    <item android:drawable= "@drawable/title_bk" ></item></selector>

2, Btn_top_pressed.xml

<?xml version= "1.0" encoding= "Utf-8"? ><shape xmlns:android= "Http://schemas.android.com/apk/res/android"    android:shape= "Rectangle" >    <gradient        android:angle= "android:endcolor="        #009ad6 "        android:startcolor= "#11264f"/></shape>

3, Dot_focused.xml

<?xml version= "1.0" encoding= "Utf-8"? ><shape xmlns:android= "Http://schemas.android.com/apk/res/android"    android:shape= "Oval" >    <solid android:color= "#aaFFFFFF"/>    <corners android:radius= "5dip" /></shape>

4, Dot_normal.xml

<?xml version= "1.0" encoding= "Utf-8"? ><shape xmlns:android= "Http://schemas.android.com/apk/res/android"    android:shape= "Oval" >    <solid android:color= "#33000000"/>    <corners android:radius= "5dip" /></shape>

5, Title_bk.xml

<?xml version= "1.0" encoding= "Utf-8"? ><shape xmlns:android= "Http://schemas.android.com/apk/res/android"    android:shape= "Rectangle" >    <gradient        android:angle= "android:endcolor="        #11264f "        android:startcolor= "#009ad6"/></shape>

6, Styles.xml (placed under the values folder)

<?xml version= "1.0" encoding= "Utf-8"?><resources>    <style name= "Dot_style" >        <item Name = "Android:layout_width" >5dip</item>        <item name= "Android:layout_height" >5dip</item>        <item name= "Android:background" > @drawable/dot_normal</item>        <item name= "Android:layout_ MarginLeft ">1.5dip</item>        <item name=" Android:layout_marginright ">1.5dip</item>    </style></resources>

I don't understand the code above, but the goal is to manipulate the smaller dots.

Here's the question, Java code. Don't worry, it's up.

Under the high energy, timid mistake into.

Java code (all sent up, let me explain slowly)

Package Com.example.mynews;import Java.util.arraylist;import Java.util.list;import android.annotation.SuppressLint ; Import Android.app.activity;import Android.os.bundle;import android.os.handler;import Android.os.Message;import Android.util.log;import Android.view.motionevent;import Android.view.view;import Android.view.view.ontouchlistener;import Android.view.viewgroup.layoutparams;import Android.widget.ImageView; Import Android.widget.imageview.scaletype;import Android.widget.textview;import Android.widget.toast;import Android.widget.viewflipper;public class Mainactivity extends Activity{private viewflipper viewflipper;private String[ ] Titles;private TextView tv_title;private list<view> dots;float startx;float x = 0;float y = 0; @Override @suppresswa Rnings ("deprecation") protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); viewflipper = (viewflipper) Findviewbyid (r.id.details); tv_title = (TextView) Findviewbyid (R. id.title); int image[] = new int[]{r.drawable.a,r.drawable.b,r.drawable.c};for (int i=0;i<image.length;i++) { ImageView IV = new ImageView (Getapplicationcontext ()); Iv.setbackgroundresource (Image[i]); Iv.setscaletype ( Scaletype.center_inside); Iv.setlayoutparams (New Layoutparams (layoutparams.fill_parent,layoutparams.wrap_content ); Viewflipper.addview (iv);} Titles = new String[image.length];titles[0] = "Hello"; titles[1] = "&&"; titles[2] = "World";d ots = new Arraylist&lt ; View> ();d Ots.add (Findviewbyid (r.id.v_dot0));d Ots.add (Findviewbyid (R.ID.V_DOT1));d Ots.add (FindViewById ( R.ID.V_DOT2) handler.sendmessagedelayed (New Message (), Viewflipper.setontouchlistener); {@SuppressLint ("clickableviewaccessibility") @Overridepublic boolean OnTouch (View V, motionevent event) {//TODO Auto-generated Method Stubswitch (Event.getaction ()) {Case motionevent.action_down:{x = Event.getx (); Toast.maketext (Getapplicationcontext (), "Down" +event.getx (), 1). Show (); Break;case MotioneVent. Action_up:{y = Event.getx (); if (y>x) {LOG.V (null, "result:y>x"); Showpre ();} else if (x==y) {LOG.V (null, "result:y=x"); ShowDetail ();} ELSE{LOG.V (NULL, "Result:x>y"); Shownext ();}} break;} return true;});} Private Handler Handler = new Handler () {@Overridepublic void Handlemessage (Message msg) {super.handlemessage (msg);    Shownext (); handler.sendmessagedelayed (new Message (), 5000);} };p rivate void Shownext () {viewflipper.shownext (); int cur = Viewflipper.getdisplayedchild (); if (cur = = 0) {dots.get (2). Setbackgroundresource (r.drawable.dot_normal);} Else{dots.get (cur-1). Setbackgroundresource (R.drawable.dot_normal);} Dots.get (cur). Setbackgroundresource (r.drawable.dot_focused); Tv_title.settext (Titles[cur]);} private void Showpre () {viewflipper.showprevious (); int cur = Viewflipper.getdisplayedchild (); if (cur = = 2) {dots.get (0). Setbackgroundresource (r.drawable.dot_normal);} Else{dots.get (cur+1). Setbackgroundresource (R.drawable.dot_normal);} Dots.get (cur). Setbackgroundresource (r.drawable.dot_focused); tv_Title.settext (Titles[cur]);} private void ShowDetail () {Toast.maketext (Getapplicationcontext (), "X=y", 1). Show ();}}

1, first prepare the picture, here I prepared three, the initialization code is as follows:

int image[] = new int[]//the number {r.drawable.a,r.drawable.b,r.drawable.c};for (int i=0;i<image.length;i+) to store three photos with an array of type int. +)//Add three photos to Viewflipper {ImageView IV = new ImageView (Getapplicationcontext ()); Iv.setbackgroundresource (Image[i]); Iv.setscaletype (scaletype.center_inside);//Here you set the image Transform format iv.setlayoutparams (new Layoutparams (Layoutparams.fill_ parent,layoutparams.wrap_content)); Viewflipper.addview (iv);}

2, the Viewflipper set monitoring events (the core of the gesture operation), note that the monitoring here is not onclicklistener, but Ontouchlistener

Viewflipper.setontouchlistener (New Ontouchlistener () {@SuppressLint ("clickableviewaccessibility") @Overridepublic Boolean OnTouch (View V, motionevent event) {//TODO auto-generated method Stubswitch (Event.getaction ()) {case Motionevent . action_down://finger Press {x = Event.getx ();//global variable, receive pressed is the finger coordinates toast.maketext (Getapplicationcontext (), "Down" +event.getx (), 1). Show ();} Break;case motionevent.action_up://finger Release {y = Event.getx ();//global variable, receive release is the finger coordinates//The following is a simple logical judgment, thus distinguishing the left slide, Slide right and do not slide (that is, click event) if (y>x) {LOG.V (null, "result:y>x"); Showpre ();} else if (x==y) {LOG.V (null, "result:y=x"); ShowDetail ();} ELSE{LOG.V (NULL, "Result:x>y"); Shownext ();}} break;} return true;}});

Here to focus on, originally I did not use this method, but the activity using the Ontouch interface, viewflipper use Onclicklistener, but also declare a gesturedetector variable, so there will be a problem, is the Ontouch and the OnClick event will affect each other, specifically what happened, I also did not understand. There are events that will study the study carefully. In addition, the complexity is increased if you use Gesturedetector.

Then there is the image switching action, which is the Showpre (), Shownext (), ShowDetail () method in the previous section of the code. The function is to Zoli, to the right, not slippery (here can be used to implement the Click event) code as follows:

private void Shownext () {viewflipper.shownext ();//sdk encapsulated well, use very convenient int cur = viewflipper.getdisplayedchild (); if (cur = = 0) {Dots.get (2). Setbackgroundresource (R.drawable.dot_normal);//This is the control of those small dots, logic should be able to understand, do not explain the}else{dots.get (cur-1). Setbackgroundresource (r.drawable.dot_normal);} Dots.get (cur). Setbackgroundresource (r.drawable.dot_focused); Tv_title.settext (Titles[cur]);} private void Showpre () {viewflipper.showprevious ();//sdk encapsulated well, use very convenient int cur = viewflipper.getdisplayedchild (); if (cur = = 2) {dots.get (0). Setbackgroundresource (R.drawable.dot_normal);} Else{dots.get (cur+1). Setbackgroundresource (R.drawable.dot_normal);} Dots.get (cur). Setbackgroundresource (r.drawable.dot_focused); Tv_title.settext (Titles[cur]);} private void ShowDetail () {Toast.maketext (Getapplicationcontext (), "X=y", 1). Show ();

Here is another point, the handler mechanism, in fact, and the timer is almost (at least here)

Handler.sendmessagedelayed (New Message (), 5000);

No 5000ms is also 5s send a message, what is the message? Please look at the lower code

Private Handler Handler = new Handler () {@Overridepublic void Handlemessage (Message msg) {super.handlemessage (msg); Shownext (); handler.sendmessagedelayed (new Message (), ();}    };

Simply put, it is to send a message to himself, reminding himself that time is up, and that he should take his medicine (to do something). And then you have to tell yourself that after the 5s also take medicine, so have been taking medicine, do not give up treatment.

I think, when it comes to this, it should be understood that the function of this code is to achieve automatic image switching.

At this point, the key part of the code is explained. As for the title and those small dot how to deal with, all in those three methods written well, certainly can see understand, not more repeat.

Report:

1, the code out the problem try not to find me, although I wrote, but its own long crooked.

2, reprint please indicate the source.

Thank you for reading and you are welcome to criticize.

  

  

  

  

Android enables ad rotation via Viewflipper and can be toggled via gesture swipe

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.