Custom controls implement AD head Auto-movement, Viewpager use, and self-use XML drawing, custom dots, and method of constructing selectors

Source: Internet
Author: User

1, Viewpager in the advertising head is often applied to, it is android3 after the appearance of the control, At the time of Android.support.v4.view.ViewPager.class, therefore, it is necessary to add the full name when the XML is defined, and be careful not to suffix the name class. The following from the demo to learn the use of Viewpager.

<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 "Android:paddi ngbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools:    context= "Com.example.viewdemo.mainactivity$placeholderfragment" android:background= "@android: Color/darker_gray"         > <android.support.v4.view.viewpager android:id= "@+id/img_view" android:layout_width= "Fill_parent" android:layout_height= "200DP"/> <!--here Background set the value for RGB, preceded by the transparency parameter, 33 is translucent--and &L T LinearLayout android:layout_width= "fill_parent" android:layout_height= "Wrap_content" Android:orienta tion= "vertical" android:background= "#33000000" android:layout_alignbottom= "@+id/img_view" > <textview android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:layout_gravity= "Center_horizontal" Android:tex                Tcolor= "@android: Color/white" android:paddingtop= "5DP" android:id= "@+id/title"/>             <!--define an empty linear layout here, add a point UI to the code, notice that gravity is arranged in a container, and that the UI is the arrangement of the UI in its layout--and <linearlayout Android:id= "@+id/dians" android:layout_width= "fill_parent" android:layout_height= "Wrap_c Ontent "android:orientation=" horizontal "android:gravity=" Center_horizontal "Android:padd Ingbottom= "10DP" android:layout_margintop= "2DP" > </LinearLayout> </linearlayo Ut> </RelativeLayout>

2, Java's activity code:

public class Mainactivity extends Activity {private Viewpager viewpager;private ArrayList <ImageView> imageviews; private int number;private view[] points;private linearlayout dians;private string[] titles;private TextView title; Private Boolean flag=true;//identifies whether the application is visible public Handler handler=new Handler () {@Overridepublic void Handlemessage ( Message msg) {int a=msg.what;points[a].setenabled (true); A++;int C=a%number;viewpager.setcurrentitem (c);    Title.settext (Titles[c]);p oints[c].setenabled (false); Super.handlemessage (msg);}};        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Dians= (LinearLayout) Findviewbyid (R.id.dians);        Title= (TextView) Findviewbyid (r.id.title);        number=5;        Initview ();        Viewpager.setonpagechangelistener (New Pagerlisetner ());                Setpointsonclick ();        Thread Pagermove=new Thread (new Threadpagechange ()); PagerMove.start (); } class Threadpagechange implements Runnable {@Overridepublic void run () {while (true) {synchronized (mainactivit Y.class) {if (flag) {try {thread.sleep ()} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} int A=viewpager.getcurrentitem (); Message msg=new message (); Msg.what=a;handler.sendmessage (msg);}        Elsetry {MainActivity.class.wait ();} catch (Interruptedexception e) {e.printstacktrace ();}}}} }//page change Listener class Pagerlisetner implements onpagechangelistener{@Overridepublic void onpagescrollstatechanged (int arg0 {} @Overridepublic void onpagescrolled (int arg0, float arg1, int arg2) {} @Overridepublic void onpageselected (int arg0) {T Itle.settext (titles[arg0]); for (int x=0;x<number;x++) {View v=dians.getchildat (x); if (x==arg0) v.setenabled (False ); elsev.setenabled (True);}}} Set point clicked Listener public void Setpointsonclick () {for (int x=0;x<number;x++) {View v=points[x];v.settag (x); V.setonclicklistener (New PointOnclicklinstener ());}} Click the Listener class Pointonclicklinstener implements onclicklistener{@Overridepublic void OnClick (View v) { System.out.println ("Clicked ... "+v.gettag ()"), int index= (Integer) V.gettag (), Title.settext (Titles[index]);p oints[index].setenabled (true); Viewpager.setcurrentitem (index);}} Initialize interface public void Initview () {//Create a imgeview for each picture, co-exist int[] images={r.drawable.a, r.drawable.b, R.dra    WABLE.C, R.DRAWABLE.D, R.DRAWABLE.E};    Imageviews=new arraylist<imageview> ();    for (int. i=0;i<number;i++) {ImageView im=new ImageView (this);    Im.setbackground (Getresources (). getdrawable (Images[i]));    Imageviews.add (IM);         } viewpager= (Viewpager) Findviewbyid (R.id.img_view);    Viewpager.setadapter (New Vpadapter ());    Add point addpoints ();    Initialize title AddTitle ();    Title.settext (Titles[0]);        Points[0].setenabled (FALSE); }//add point public void Addpoints () {points=new view[number];for (int i=0;i<number;i++) {View v=newView (this);     Create a child view Layoutparams pa=new Layoutparams (8, 8);     pa.leftmargin=10;     V.setlayoutparams (PA);//Make points in sub-view format to Form view V.setbackgroundresource (r.drawable.bg);//Set the background of the point, where BG is the selector, described below    V.setenabled (TRUE);     Adds the created child view point to the LinearLayout points[i]=v;    Dians.addview (v); }}//add title public void AddTitle () {titles=new string[]{"Gong Li is not vulgar, I can not vulgar", "Park Tree mail back!" Sing the classic old songs cited million people chorus "," secret Beijing film How to Upgrade "," Le video network TV version of the big delivery "," blood cock silk anti-killing "}; Class Vpadapter extends pageradapter{@Overridepublic Object instantiateitem (viewgroup container, int position) { Viewpager.addview (Imageviews.get (position)); return imageviews.get (position);} @Overridepublic void Destroyitem (ViewGroup container, int position, object object) {//From right to left to delete the current page, add from right to left That is, the execution of Instantiateitem, when 1 time jumped to 5 o'clock, actually add the front 4 (only my view) Viewpager.removeview (Imageviews.get (position));} @Overridepublic int GetCount () {return imageviews.size ();} @Overridepublic boolean isviewfromobject (View arg0, Object arg1) {return arg0==arg1;}} Overriding the activity lifecycle below is when the program is behind the scenes in order to consume resources and let the child threads wait for @overrideprotected void Onresume () {if (!flag) MainActivity.class.notify (); Super.onresume ();} @Overrideprotected void OnPause () {flag=false;super.onpause ();}}

3, the following describes how to draw in the XML file, first give my project directory:

As can be seen, the file defines the Dian_normal, and Dian_select, which is the point in the selection and is not selected when the image, BG is actually the two images of the selector, when you can click on the normal, not click to display Select. Drawing is to choose shape in drawable, and then you can draw several simple shapes:

Normal XML file: Android:shape=oval is the finger circle, and the radius below is corners radius, solid is the fill color.

<?xml version= "1.0" encoding= "Utf-8"? ><shape xmlns:android= "Http://schemas.android.com/apk/res/android"     android:shape= "Oval" >    <corners         android:radius= "0.5DP"        />        <solid             android: Color= "@android: Color/background_dark"            />   </shape>

The XML file for select

<?xml version= "1.0" encoding= "Utf-8"? ><shape xmlns:android= "Http://schemas.android.com/apk/res/android"     android:shape= "Oval" >    <corners         android:radius= "0.5DP"        />        <solid             android: Color= "@android: Color/white"            /></shape>

Here is the selector: Db.xml, which is when Enable=true chooses a drawable,false time to select another

<?xml version= "1.0" encoding= "Utf-8"? ><selector xmlns:android= "http://schemas.android.com/apk/res/ Android ">    <item android:state_enabled=" false "android:drawable=" @drawable/dian_select "></item ><item android:state_enabled= "true" android:drawable= "@drawable/dian_normal" ></item></selector >

  

Custom controls implement AD head Auto-movement, Viewpager use, and self-use XML drawing, custom dots, and method of constructing selectors

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.