Scrolling banner for Android custom controls

Source: Internet
Author: User
Tags thread stop

On some e-commerce sites, you can often see some rolling banners, and many software have similar banners for the first time,

There's actually a control on GitHub that does this, but it's easy to do, and we'll see what we can do today.

Let's take a look at the layout file:

<relativelayout  xmlns: Android  = "http://schemas.android.com/apk/res/android"  xmlns:tools  =" Http://schemas.android.com/tools " android:layout_width  = "match_parent"  android:layout_height  =" match_parent " tools:context  =" com.example.customwidget2.MainActivity "     <android.support.v4.view.viewpager  android:id  =" @+id/viewpager " android:layout_width  = "wrap_content"  android:layout_height  = "200DP" />     <linearlayout  android: Layout_width  = "match_parent"  android:layout_ Height  = "wrap_content"  android:layout_ AlignBottom  = "@id/viewpager"  android: Background  = "#33000000"  android:orientation< /span>= "vertical"  android:padding  = "5DP" ;         <textview  android:id= "@+id/image_description"  android:layout_width< /span>= "wrap_content"  android:layout_height  = "wrap_content"  android:layout_gravity  =
       
         "center_horizontal" 
        android:text  =" Huai Zuo, Jukseoru Jia, the solution saddle less stationed in the first journey. " android:textcolor  =" @android: Color/white " /span>/>         <linearlayoutandroid:id="@+id/show_pointer"android:layout_width= "Wrap_content" android:layout_height="Wrap_content"android:orientation="Horizontal"  Android:layout_gravity="Center_horizontal" >                                                             </linearlayout>    </linearlayout></relativelayout>

The top of the layout file is a viewpager, using Viewpager to achieve the scrolling effect of the picture, Viewpager below is a linearlayout, this layout file has two things, one is TextView, which is used to display the line below the word, There is also a linearlayout, which is used to display the lower point of the word, the number of small dots we have to dynamically add according to the number of pictures, so now first empty.

Mainactivity.java

 Public  class mainactivity extends Activity {    PrivateViewpager Mviewpager;//pictures are stored here    PrivateList<imageview> imageviewlist;PrivateImageView IV;PrivateTextView Imgdes;//thread switch, when the activity is destroyed, the thread should also stop running    Private BooleanIsstop =false;Private intPreviouspoint =0;//Store small point layout file    PrivateLinearLayout Layoutpgroup;PrivateString[] Imagedescription = {"Huai left name, Jukseoru good place, the solution saddle less stationed in the first journey." ","Over the spring breeze ten miles." Camelina the green wheat. ","Since the horses peep the river to go, the waste pond tree, still hates the word soldier." ","Gradually dusk, the clear angle blows the cold." are in the empty city. ","Durongjun reward, Count now, the heavy to be startled." "};@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main);//InitializeInit ();//Set the picture to scroll automatically        NewThread (NewRunnable () {@Override             Public void Run() {//If activity is not destroyed it is always executed                 while(!isstop) {//Rest for 5 seconds firstSystemclock.sleep ( the);//The following code is sent to the main thread to executeRunonuithread (NewRunnable () {@Override                         Public void Run() {Mviewpager.setcurrentitem (Mviewpager. Getcurrentitem () +1);                }                    });    }}). Start (); }Private void Init() {Mviewpager = (Viewpager) This. Findviewbyid (R.id.viewpager); Layoutpgroup = (linearlayout) This. Findviewbyid (R.id.show_pointer); Imgdes = (TextView) This. Findviewbyid (R.id.image_description); Imageviewlist =NewArraylist<imageview> ();//Get the image ID first        int[] Ivids =New int[] {r.drawable.a, r.drawable.b, r.drawable.c, R.DRAWABLE.D, R.DRAWABLE.E};//Traverse image ID         for(intId:ivids) {//Construct a new picture object and set the background for the picture by IDIV =NewImageView ( This); Iv.setbackgroundresource (ID);//All the pictures are stored in imageviewlistImageviewlist.add (iv);//Construction Small pointView v =NewView ( This);//Set the width and height of small dotsLayoutparams params =NewLayoutparams (8,8);//Set the left margin of the dotParams.leftmargin = A; V.setlayoutparams (params);//Set whether the dot is available, default is unavailable, when not available, the dot is transparent, otherwise it is whiteV.setenabled (false);//Set the background of the dot, this background is a small dot drawn using an XML fileV.setbackgroundresource (R.drawable.pointer_selector);//Add small dots to its layout fileLayoutpgroup.addview (v); }//Calculate the first item displayed when the app is opened INTEGER.MAX_VALUE/2-3=0        intindex = integer.max_value/2-3;//Set data for MviewpagerMviewpager.setadapter (NewMypageradapter ());//Set page swipe events for MviewpagerMviewpager.setonpagechangelistener (NewMyonpagechangelistener ());//Set the first item that appears when the app is opened, and the value of index is 0        //Use this method to get 0, and direct write 0 What is the difference?         ///Direct write 0, the application cannot be opened directly to the right, because the Viewpager in the image position can not be negative, can only swipe left first        //This method gets 0, can be implemented once the application is open, you can swipe rightMviewpager.setcurrentitem (index); }Private  class Myonpagechangelistener implements Onpagechangelistener {        //Start        @Override         Public void onpagescrollstatechanged(intarg0) {}//IS in progress        @Override         Public void onpagescrolled(intARG0,floatArg1,intARG2) {}//End        @Override         Public void onpageselected(intPosition) {//When the page slide is finished, first model the page positionPosition = position% imageviewlist.size ();//Set the text content of TextViewImgdes.settext (Imagedescription[position]);//Set the availability of the previous point to falseLayoutpgroup.getchildat (Previouspoint). setenabled (false);//Set the availability of the current point to trueLayoutpgroup.getchildat (position). setenabled (true);//Assign the current position value to PreviouspointPreviouspoint = position; }    }Private  class mypageradapter extends pageradapter {        /** * Returns the total number of pictures, the value of Integer.max_value is 2147483647 this number has 2.1 billion, that is to say, our viewpager * Theoretically in each use of the application can be sliding 2.1 billion times, of course, no one actually To do this, we do this in order to achieve the effect of Viewpager loop sliding * that is, when sliding to the last page of Viewpager, continue to swipe to go back to the first page * */        @Override         Public int GetCount() {returnInteger.max_value; }@Override         Public Boolean Isviewfromobject(View arg0, Object arg1) {returnarg0 = = Arg1; }//When a page slides out, destroy it        @Override         Public void Destroyitem(ViewGroup container,intPosition, Object object) {Container.removeview (imageviewlist.get (position% IMAGEVIEWLIST.S        Ize ())); }//Add a picture to the container, because we want to achieve the effect of circular sliding, so we have to take the model of position        @Override         PublicObjectInstantiateitem(ViewGroup container,intPosition) {container. AddView (imageviewlist.get (position% imageviewlist.size ()));returnImageviewlist.get (position% imageviewlist.size ()); }    }//When the activity is destroyed, let the thread stop    @Override    protected void OnDestroy() {isstop =true;Super. OnDestroy (); }}

The comments in the code have been described in detail, and I will not repeat them.

Unselected Small dot pointer_disable.xml:

<?xml version= "1.0" encoding= "Utf-8"?  <shape  xmlns: Android  = "http://schemas.android.com/apk/res/android"  android:shape  =" oval ";     <!--set the fillet radius-->  <corners  android:radius  =/>  <!--set the color of the fill--  <solid  android: Color  = "#55000000" />  </shape ;   

Small dot Pointer_focus.xml When selected:

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"    android:shape="oval" >    <corners android:radius="0.5dip" />    <solid android:color="#aaFFFFFF" /></shape>

Small dots selector:

<?xml version= "1.0" encoding= "Utf-8"?><selector xmlns:android="Http://schemas.android.com/apk/res/android" >    <!--selected, small dots are white--    <item android:state_enabled="true" android:drawable="@drawable /pointer_focus "></Item>    <!--is not selected, the dot is transparent--    <item android:state_enabled="false" android:drawable="@drawable/ Pointer_disable "></Item></selector>

Full code download for this project

Scrolling banner for Android custom controls

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.