Android Custom Control Case Rollup 1 (menu, Popupwindow, Viewpager) _android

Source: Internet
Author: User
Tags object object static class

Custom controls write controls to their own needs. Android's own controls sometimes don't meet your needs, and at this point we can only implement the controls that fit the project. At the same time, Android allows you to inherit existing controls or implement your own controls to optimize the interface and create a richer user experience. In the usual project, we artificially divide the custom control into two kinds: one is the combination implementation. One is implemented by inheriting view or ViewGroup and its subclasses. Both can achieve the desired effect, therefore, we can according to their own needs, choose the right solution. This article shows several more common custom controls in the form of cases.

Case One Youku menu:

function Introduction: The bottom center of the mobile phone interface has a semicircle, the initial state shows level three menu, from outside to Inside is third level menu, second level menu, third level menu respectively. There are some buttons in each menu, you can use 3 containers (relativelayout) to represent 3 menus, add a button inside. Once again click on the center position of the picture-style, hide the outer two layers of entries. When you click on the image of the center of gravity again, rotate the level two menu. Click the two Level menu center position, rotate out of Level three menu, click again to hide the level three menu. The above is the function that the cool menu wants to realize.

Implementation steps:

1. Complete the layout file. The layout of the Youku menu is more complex because of more controls, but you can set up three sub linear layouts in one root layout to wrap each small control. By adjusting the margin value to make the interface more beautiful. Note the order of 3 menu layouts, first put men3, then menu2, and then menu1, the order can not be reversed, because the more you put the menu more in the top of the interface, so the smallest area of the menu 1 will be at the top, menu 1 will not block to the following menu 2 and menu 3.

2. After completing the layout file, create a class that implements the business logic in the class. First you create two Boolean-type constants to store the state of the menu. The Swich statement determines whether the clicked control is a level two menu or a primary menu. If the center of the first-order menu is clicked, determine if the level three menu is open. If the level three menu is open, hide the level menu and level two menu and modify the status. If the level three menu is hidden, determine if level two menu is hidden. If the level two menu is open, the level two menu is hidden. If level two menu is hidden, open level two menu. If the center of the level two menu is clicked, you only need to determine if level three menu is hidden. If the level three menu is open, the level three menu is hidden. If level three menu is hidden, open level three menu. Also modify the status of the menu.

3. You can then implement the animation effect in a tool class. Both the shadowing and the display in step 2 are accomplished by animating the effect. The animation effect here is a motion tween, which passes the starting angle, the ending angle, the reference object, and the reference point coordinates for the Rotateanimation object. A small detail is to set the Setfillafter property to true to indicate that the animation starts at the end position, avoiding the end of the animation and returning to the starting position. The hidden and displayed differences are the starting and ending angles of the rotation, where the starting angle of the setting is 180, and the end angle is 0. The starting angle of the hidden setting is 0, and the end angle is-180. Of course, it can be set to other values, depending on the effect you want.

4. Code optimization. When you click the button quickly, you will see that the menu has not been hidden, or it has not been shown yet and hidden. Solution: Monitor the number of times the animation is turned on to determine whether a painting needs to be performed and add a listener to the animation class. Set a member variable. When the start of the animation is performed by adding an action, the end animation is performed minus one operation. This will not animate unless the constant is zero. So add in the Swich statement if there is currently an animation, wait until the animation is finished before entering the following logic.

Layout of menu Selection interface:

<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout xmlns:android= "http://schemas.android.com/apk/res/" Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "> <relativelayout androi D:id= "@+id/rl_menu3" android:layout_width= "280DP" android:layout_height= "140DP" Android:layout_alignparentbott
      Om= "true" android:layout_centerhorizontal= "true" android:background= "@drawable/level3" > <imagebutton Android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:layout_alignparentbottom= "True" android:layout_marginbottom= "6DP" android:layout_marginleft= "12DP" android:background= "@drawable/
      Channel1 "/> <imagebutton android:layout_width= wrap_content" android:layout_height= "Wrap_content" Android:layout_alignparentbottom= "true" android:layout_marginbottom= "46DP" android:layout_marginleft= "32 DP "android:background=" @Drawable/channel2 "/> <imagebutton android:layout_width=" wrap_content "android:layout_height=" Wrap_ Content "android:layout_alignparentbottom=" true "android:layout_marginbottom=" 80DP "Android:layout_margi nleft= "60DP" android:background= "@drawable/channel3"/> <imagebutton android:layout_width= "Wrap_con Tent "android:layout_height=" Wrap_content "android:layout_centerhorizontal=" true "Android:layout_margint op= "6DP" android:background= "@drawable/channel4"/> <imagebutton android:layout_width= "wrap_content "Android:layout_height=" Wrap_content android:layout_alignparentbottom= "true" Android:layout_alignparen Tright= "true" android:layout_marginbottom= "80DP" android:layout_marginright= "60DP" android:background= "@ Drawable/channel5 "/> <imagebutton android:layout_width=" wrap_content "android:layout_height=" Wrap_ Content "Android:lAyout_alignparentbottom= "true" android:layout_alignparentright= "true" android:layout_marginbottom= "46DP" android:layout_marginright= "32DP" android:background= "@drawable/channel6"/> <imagebutton android:
      Layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:layout_alignparentbottom= "true"
      Android:layout_alignparentright= "true" android:layout_marginbottom= "6DP" android:layout_marginright= "12DP" android:background= "@drawable/channel7"/> </RelativeLayout> <relativelayout android:id= "@+id/rl
    _menu2 "android:layout_width=" 180DP "android:layout_height=" 90DP "android:layout_alignparentbottom=" true " Android:layout_centerhorizontal= "true" android:background= "@drawable/level2" > <imagebutton android:la Yout_width= "Wrap_content" android:layout_height= "Wrap_content" android:layout_alignparentbottom= "true" a Ndroid:layout_marginbottOm= "6DP" android:layout_marginleft= "12DP" android:background= "@drawable/icon_search"/> <imagebutto
      n android:id= "@+id/btn_menu2" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:layout_centerhorizontal= "true" android:layout_margintop= "4DP" android:background= "@drawable/icon_
      Menu "/> <imagebutton android:layout_width=" wrap_content android:layout_height= "Wrap_content" Android:layout_alignparentbottom= "true" android:layout_alignparentright= "true" android:layout_marginbottom= " 6DP "android:layout_marginright=" 12DP "android:background=" @drawable/icon_myyouku "/> </relativelayou t> <relativelayout android:id= "@+id/rl_menu1" android:layout_width= "100DP" android:layout_height= "50d P "android:layout_alignparentbottom=" true "android:layout_centerhorizontal=" true "android:background=" @drawabl E/level1 "> <iMagebutton android:id= "@+id/btn_menu1" android:layout_width= wrap_content "android:layout_height=" Wrap_c Ontent "android:layout_centerinparent=" true "android:background=" @drawable/icon_home "/> </relativela


 Yout> </RelativeLayout>

The layout of the main interface, in the code with a pump to the menu layout to the main interface.

<?xml version= "1.0" encoding= "Utf-8"?> <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:gravity= "center"
  tools:context= " Com.example.selectbar.Selectbar ">

  <com.example.selectbar.rotate
    android:layout_centerinparent=" True "
    android:id=" @+id/rotate "
    android:layout_width=" wrap_content "
    android:layout_height=" Wrap_ Content "/>

</RelativeLayout>


The main program is an empty implementation.

Import Android.os.Bundle;
Import android.support.v7.app.AppCompatActivity;

public class Selectbar extends Appcompatactivity {

  @Override
  protected void onCreate (Bundle savedinstancestate ) {
    super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_selectbar);
  }



The implementation of the main logic.

Import Android.content.Context;
Import Android.util.AttributeSet;
Import Android.util.Log;
Import Android.view.View;

Import Android.widget.RelativeLayout;

Import Com.example.selectbar.com.example.selectbar.utils.utils;
 /** * Created by Huang on 2016/11/22. * * public class Rotate extends Relativelayout implements View.onclicklistener {private static final String TAG = "Rotat
  E ";
  Private Relativelayout rl_menu1, RL_MENU2, RL_MENU3;
  Private Boolean menu2showing = true;

  Private Boolean menu3showing = true;
  Public Rotate {super (context,null);
    Public Rotate (context, AttributeSet attrs) {Super (context, attrs);
  InitData (context);
    private void InitData (context context) {LOG.I (TAG, "Initdata:text");
    View view = View.inflate (Context,r.layout.activity_rolate,null);
    View.findviewbyid (r.id.btn_menu1). Setonclicklistener (this);
    View.findviewbyid (R.ID.BTN_MENU2). Setonclicklistener (this); rl_menu1 = (RelativelayoUT) View.findviewbyid (R.ID.RL_MENU1);
    RL_MENU2 = (relativelayout) View.findviewbyid (R.ID.RL_MENU2);
    RL_MENU3 = (relativelayout) View.findviewbyid (R.ID.RL_MENU3);
  AddView (view); @Override public void OnClick (View v) {switch (V.getid ()) {Case R.id.btn_menu2:if (Utils.hasani
        Mationexcuting ()) {return;
        } if (menu3showing) {Utils.hiden (RL_MENU3);
        else {utils.show (RL_MENU3);
        } menu3showing =!menu3showing;

      Break
        Case R.id.btn_menu1:if (utils.hasanimationexcuting ()) {return;
          } if (menu3showing) {Utils.hiden (RL_MENU3);
          Menu3showing = false;

        Utils.hiden (RL_MENU2, 300);
        else if (menu2showing) {Utils.hiden (RL_MENU2);
        else {utils.show (RL_MENU2);
        } menu2showing =!menu2showing;
    Break


 }
  }
}

You also need a tool class to implement the animation effect.

Import Android.view.View;
Import Android.view.ViewGroup;
Import android.view.animation.Animation;

Import android.view.animation.RotateAnimation;
 /** * Created by Huang on 2016/11/22.
  * * Public class Utils {private static final String TAG = "Utils";
    private static void setviewclickable (View view, Boolean clickable) {view.setclickable (clickable);
      if (view instanceof viewgroup) {ViewGroup ViewGroup = (viewgroup) view;
        for (int i = 0; i &lt; Viewgroup.getchildcount (); i++) {View child = (viewgroup) view). Getchildat (i);
      Child.setclickable (clickable);
    }} public static void Hiden (view view) {float Fromdegreeas = 0;
    float todegrees = -180f;
    Rotateview (view, Fromdegreeas, Todegrees, 0l);
  Setviewclickable (view, false);
    public static void Hiden (view view, long Startoffset) {float fromdegreeas = 0;
    float todegrees = -180f;
    Rotateview (view, Fromdegreeas, Todegrees, Startoffset); SetviewclickaBle (view, false);
    public static void Show (view view) {float fromdegrees = -180f;
    float todegrees = 0;
    Rotateview (view, Fromdegrees, Todegrees, 0l);
  Setviewclickable (view, true);
  public static Boolean hasanimationexcuting () {return startcount &gt; 0;  public static void Rotateview (view view, float fromdegrees, float todegrees, long startoffset) {int pivotxtype =
    rotateanimation.relative_to_self;
    int pivotytype = rotateanimation.relative_to_self;
    float pivotxvalue = 0.5f;
    float pivatyvalue = 1.0f;
    Rotateanimation ra = new Rotateanimation (fromdegrees, Todegrees, Pivotxtype, Pivotxvalue, Pivotytype, PivatYValue);
    Ra.setduration (500);
    Ra.setfillafter (TRUE);
    Ra.setstartoffset (Startoffset);
    Ra.setanimationlistener (listener);
  View.startanimation (RA);
  public static int startcount; Static Animation.animationlistener listener = new Animation.animationlistener () {@Override public void Onanimatio NStArt (Animation Animation) {startcount++;//LOG.I (TAG, "Onanimationstart:" +startcount); @Override public void Onanimationend (Animation Animation) {startcount--;//LOG.I (TAG, "onanimation
    End: "+ Startcount";
@Override public void Onanimationrepeat (Animation Animation) {}};


 }

Case Two Popupwindow Implementation Drop-down list:

Feature Description: Create a TextView, when we click on the TextView will pop up a list, the list is stored in digital information and a delete picture. The list is implemented with ListView. Click to delete a picture to remove this record from the list. There are two kinds of this case, one is the animation through the zoom to achieve pop-up effect, the other is to take Popupwindow. The second scheme is used in this paper.

Implementation steps:

Add a layout file. First, place a textview on the interface and place a drop-down picture on the right side of the TextView. In order to place the control more conveniently, the relative layout can be used, so as long as the ImageView and TextView alignment, alignment, right alignment can achieve the realistic effect. To make the interface more beautiful, you can set the picture to be transparent, that is, the background is null. Here the Popupwindow of the interface is shown in ListView. So write a separate ListView and the layout of each item, and then use a pump to hit the bottom of the TextView,


The writing of Pupupwindow. Popupwindow's writing has two key steps, one is a new Pupupwimdow object, the layout to be displayed, the layout of the high and wide, whether or not the parameters related to the incoming. Here the Pupupwindow display interface is a pump to load the ListView in. The layout of the ListView entry is also used for inflate. So use two times to pump. At the same time, set entries for each ListView item click on the Listener event, so that when the entry is clicked can display the contents of the item in the TextView. Another key step in Popupwindow's writing is the Showasdropdown, which is about to be displayed under which control, and how much of the offset is passed in. It is important to note that the actual width of the control and the width of the saw have certain errors, just because the background of the control with a certain width. Another thing is, press the return key when Popupwindow can not hide, to Popupwindow set a background to solve this problem, as follows: Popupwindow.setbackgrounddrawable (new Colordrawable () )。 A new Popupwindow object is created each time the Popupwindow is displayed, and a Popupwindow object can actually be reused. That is, to determine whether Popupwindow is empty before each creation.


The preparation of Listiview entries is more definite. Here are two optimizations. One is to take the Conterview, before starting the operation to determine whether the Conterview is empty. If you create a new view for empty, reuse the recycled conterview. Another optimization is that each time the Finviewbyid consumes a lot of memory. You can therefore define a single class, hold the control, and create it once when Cnterview is empty. You only need to call the controls in the definition class each time you call. Also, if the deletion icon on the entry is useful, set a click event on the delete picture. A small detail is that when the button and its subclasses exist in the Listvie entry, the focus is preempted. So the label for removing the picture here is ImageView. Of course you can also take other ways, for example, in the root layout of the entry plus this attribute: android:descendantfocusability= "blocksdescendants".


Layout of the main interface:

&lt;?xml version= "1.0" encoding= "Utf-8"?&gt; &lt;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:layout_margin= "17DP" android:paddingbottom= "@dimen/activity_vertical_margin" Android: paddingleft= "@dimen/activity_horizontal_margin" android:paddingright= "@dimen/activity_horizontal_margin" Android :p addingtop= "@dimen/activity_vertical_margin" tools:context= "com.example.popuwindow.MainActivity" &gt; &lt;
      Relativelayout android:layout_width= "match_parent" android:layout_height= "wrap_content" &gt; &lt;EditText Android:id= "@+id/et_number" android:layout_width= "200DP" android:layout_height= "Wrap_content" Android: Hint= "Enter account"/&gt; &lt;imagebutton android:layout_width= "Wrap_content" android:layout_height= "Android:layout_alignbottom=" @id/et_number "android:layout_alignright= "@id/et_number" android:layout_aligntop= "@id/et_number" android:background= "@null" android:onclick= "Shownumberlisttoggle" android:src= "@mipmap/down_arrow"/&gt; &lt;/RelativeLayout&gt; &lt;/rel


 Ativelayout&gt;

Layout of ListView Entries

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
  android:layout_width=" match_parent "
  android:layout_height=" Wrap_content "
  android: Gravity= "center_vertical"
  android:orientation= "horizontal"
  android:padding= "6DP" >

  <imageview
    android:layout_width= "wrap_content"
    android:layout_height= "wrap_content"
    android:src= "@mipmap User "/>

  <textview
    android:id=" @+id/tv_numer "
    android:layout_width=" 0DP "
    android: layout_height= "Wrap_content"
    android:layout_marginleft= "6DP"
    android:layout_weight= "1"
    android: Text= "10000"
    android:textsize= "18sp"/>

  <imageview android:id=
    "@+id/ib_del"
    android: Layout_width= "Wrap_content"
    android:layout_height= "wrap_content"
    android:background= "@null"
    android:src= "@mipmap/delete"/>
</LinearLayout>


Write a ListView alone.

<?xml version= "1.0" encoding= "Utf-8"?> <listview xmlns:android=
"http://schemas.android.com/apk/res/" Android "
  android:layout_width=" match_parent "
  android:layout_height=" Wrap_content "
  android: Cachecolorhint= "@null"
  android:background= "@mipmap/listview_background"
  android:descendantfocusability = "Blocksdescendants" >
</ListView> 

Logic in the main program.

Import android.graphics.drawable.ColorDrawable;
Import Android.os.Bundle;
Import android.support.v7.app.AppCompatActivity;
Import Android.view.View;
Import Android.widget.AdapterView;
Import Android.widget.EditText;
Import Android.widget.ListView;

Import Android.widget.PopupWindow;
  public class Mainactivity extends Appcompatactivity {private EditText et_number;

  Private Popupwindow Popupwindow;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main);
  Et_number = (edittext) Findviewbyid (R.id.et_number); public void Shownumberlisttoggle (view view) {if (Popupwindow = = null) {//multiplexing Popupwindow View cont
      Entview = Createcontent ();
      int width = et_number.getwidth ()-4;
      int height = 400;
      Boolean focusable = true;
      Popupwindow = new Popupwindow (contentview, width, height, focusable); Popupwindow.setbackgrounddrawable (New colordrawable ());
    View anchor = Et_number;
    int xoff = 2;
    int yoff =-5;
  Popupwindow.showasdropdown (anchor, Xoff, Yoff);
      Private View createcontent () {ListView LV = (ListView) view.inflate (this, r.layout.activity_list, null);
      Lv.setadapter (New Numberlistadapter ());
      Lv.setverticalscrollbarenabled (FALSE);
    Lv.setonitemclicklistener (Monitemclicklistener);
  return LV; } adapterview.onitemclicklistener Monitemclicklistener = new Adapterview.onitemclicklistener () {@Override Publ IC void Onitemclick (adapterview&lt;?&gt; parent, view view, int position, long id) {String number = (string) parent
      . getitematposition (position);
      Et_number.settext (number);
    Popupwindow.dismiss ();
}
  };


 }

The preparation of adapter

Import Android.view.View;
Import Android.view.ViewGroup;
Import Android.widget.BaseAdapter;
Import Android.widget.ImageView;

Import Android.widget.TextView;

Import java.util.ArrayList;
 /** * Created by Huang on 2016/11/22.
  
  * * public class Numberlistadapter extends Baseadapter {private arraylist&lt;string&gt; numbers = new ArrayList ();
    {for (int i = 0; i &lt; i++) {Numbers.add (10000 + i + "");
  @Override public int GetCount () {return numbers.size ();
  @Override public Object getitem (int position) {return numbers.get (position);
  @Override public long getitemid (int position) {return position;
    @Override public view GetView (final int position, view Convertview, ViewGroup parent) {view view;
    Viewholder Holder;
      if (Convertview = = null) {view = View.inflate (Parent.getcontext (), r.layout.item_number_list,null);
      Holder = new Viewholder (); Holder.ib_del = (ImageView) View.findviewbyid (R. Id.ib_del);
      Holder.tv_number = (TextView) View.findviewbyid (R.id.tv_numer);
    View.settag (holder);
      }else{view = Convertview;
    Holder = (viewholder) view.gettag ();
    } holder.ib_del.setImageResource (R.mipmap.delete);
    Holder.tv_number.setText (Numbers.get (position));
        Holder.ib_del.setOnClickListener (New View.onclicklistener () {@Override public void OnClick (View v) {
        Numbers.remove (position);
      Notifydatasetchanged ();
    }
    });
  return view;
     Static class viewholder{TextView Tv_number;
  ImageView Ib_del;  

 }
}

Case Three Viewpager Implementation of the Carousel map:

Function Introduction: The realization of advertising bar, also known as the Carousel map. At the top of the mobile interface, put a viewpager function to achieve the interface of the left and right sliding. Sliding is divided into two, one is the interval of a certain amount of time to automatically slide, while also supporting the left and right hand gestures sliding. A small detail is a small dot at the bottom of the carousel map that is equal to the number of pictures, used to indicate which picture is currently selected.
Implementation steps:

1. The layout file is composed of two parts, one is Viewpager, the other is the bottom bar and the small dot. The Viewpager exists under the V4 package and is therefore compatible with Android1.6. The bottom bars and small dots are placed in a linear layout so that they are placed at the bottom of the Viewpager, while the text and the dots are centered. Here is a special point about the realization of small dots. Small dots are made out of a shape chart. Because you cannot get the number of dots in the layout file, you can place a linearlayout in the layout file and then add the View object to the LinearLayout in Java code. Also set the status selector for white dots and black dots to the background of the view.
2. The next step is the preparation of Viewpager. The key to writing Viewpager is the write adapter. Write a class to inherit pageradapter, overriding the method. Viewpager the default is to load three pictures, one in the middle of the screen, the left of the screen and one on the right side of the screen. We want the carousel graph to be looping, so you can return a large enough value to the GetCount, and when you initialize the carousel map, set the initial position of the carousel to the middle so that you can loop it. When we set the GetCount return value to a very large value, the position is also judged in the Instantiateitem. The incoming position is a great value, but the number of pictures is really limited, so you can take the position, so you can put the position position and the number of pictures corresponding.
3. To achieve automatic playback need to use the message mechanism, interval of three seconds to invoke the display of the next picture method. Displays the next picture is the number of the item that calls Viewpager's Setcurrentitem and passes in the next picture. When a finger slides, it viewpager itself, so there is no need to redefine it.
4. The last feature to be implemented is that the text at the bottom of the viewpager and the dots follow the changes in the picture. At this point, you can set a Viewpager listener event to change the TextView value when the picture changes. Then traverse LinearLayout's Child view (the small dots that are stored in the child view), and select the dots when the serial number of the dots and the sequence number of the pictures are always there. Of course, here also to position, the position to the picture size of the same range.

Implementation of the main interface:

&lt;?xml version= "1.0" encoding= "Utf-8"?&gt; &lt;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:paddingbottom= "@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.advertisement.MainActivity "&gt; &lt; Android.support.v4.view.ViewPager android:id= "@+id/view_pager" android:layout_width= "Match_parent" Android:lay out_height= "150DP"/&gt; &lt;linearlayout android:layout_width= "match_parent" android:layout_height= "Wrap_conte" NT "android:layout_alignbottom=" @id/view_pager "android:background=" @color/trans_balck "android:gravity=" Cente
R "android:orientation=" vertical "android:padding=" 5DP "&gt; &lt;textview      Android:id= "@+id/tv_desc" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:text= "Picture description" android:textcolor= "@android: Color/white"/&gt; &lt;linearlayout android:id= "@+id/ll_ Dots "android:layout_width=" wrap_content "android:layout_height=" wrap_content "android:orientation=" Hori

 Zontal "&gt;&lt;/LinearLayout&gt; &lt;/LinearLayout&gt; &lt;/RelativeLayout&gt;

State Selector

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

Drawing of a shape chart

<?xml version= "1.0" encoding= "Utf-8"?> <shape xmlns:android=
"http://schemas.android.com/apk/res/" Android "
 android:shape=" Oval >
   <solid android:color= "@color/trans_balck"/>
</shape>

< save space, two write down together >
<?xml version= "1.0" encoding= "Utf-8"?> <shape xmlns:android=
"http://" Schemas.android.com/apk/res/android "
 android:shape=" Oval ">
   <solid android:color=" @android: Color /white "/>
</shape>

Business logic in the main program

Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.support.v4.view.ViewPager;
Import android.support.v7.app.AppCompatActivity;
Import Android.util.Log;
Import Android.view.View;
Import Android.widget.LinearLayout;

Import Android.widget.TextView;
  public class Mainactivity extends Appcompatactivity {private static final String TAG = "mainactivity";
  Private int[] Imageresids = {r.drawable.a, r.drawable.b, r.drawable.c, R.DRAWABLE.D, R.DRAWABLE.E}; Private string[] desc = {"Gong Li is not vulgar, I can not vulgar", "flutter Tree back again!"

  And then sing the classic old songs, "The Revelation of Beijing film How to Upgrade", "music video network TV version of the big delivery", "blood cock Silk's anti-Kill"};
  Private LinearLayout ll_dots;
  Private TextView Tv_desc;
  Private Viewpager Viewpager;

  private static final int show_next_page = 0;

  Private Handler Handler = new Handler ();
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main); Ll_dots = (linearlayout) Findviewbyid (R.ID.LL_DOTS);
    Tv_desc = (TextView) Findviewbyid (R.ID.TV_DESC);
    Viewpager = (Viewpager) Findviewbyid (R.id.view_pager);
    Viewpager.setadapter (New Banneraapter (Imageresids));
    Viewpager.setonpagechangelistener (listener);
    Initdot ();
    Changedotanddesc (0);
    Viewpager.setcurrentitem (Viewpager.getadapter (). GetCount ()/2);
  Handler.postdelayed (mrunnable,3000);
    Runnable mrunnable = new Runnable () {@Override public void run () {shownextpage ();
  }
  };
      /** initialization small dot/private void Initdot () {for (int i = 0; i &lt; imageresids.length; i++) {int _5DP = dp2px (5);
      Linearlayout.layoutparams params = new Linearlayout.layoutparams (_5DP, _5DP);
      Params.leftmargin = _5DP;
      View dot = new view (this);
      Dot.setlayoutparams (params);
      Dot.setbackgroundresource (R.drawable.select_dot);
    Ll_dots.addview (dot); }/** converts PD data to PX data/private int dp2px (int pd) {Float desity = getresources (). getdisplaymetrics;
  return (int) (PD * desity + 0.5f); } Viewpager.onpagechangelistener Listener = new Viewpager.onpagechangelistener () {@Override public void OnPage scrolled (int position, float positionoffset, int positionoffsetpixels) {} @Override public void Onpageselec
    Ted (int position) {Changedotanddesc (position);

  @Override public void onpagescrollstatechanged (int state) {}};
    public void Changedotanddesc (int position) {position = position% ll_dots.getchildcount ();
    Tv_desc.settext (Desc[position]);
      for (int i = 0; i &lt; Ll_dots.getchildcount (); i++) {log.i (TAG, "Changedotanddesc:" + i+ "" + position);
    Ll_dots.getchildat (i). setselected (i = = position);
    }} private void Shownextpage () {int currenitem = Viewpager.getcurrentitem ();
    Viewpager.setcurrentitem (Currenitem + 1);
  Handler.postdelayed (mrunnable,3000);

 }
}

Authoring of Adapters:

Import Android.support.v4.view.PagerAdapter;
Import Android.view.View;
Import Android.view.ViewGroup;

Import Android.widget.ImageView;
 /** * Created by Huang on 2016/11/22.

  * * public class Banneraapter extends Pageradapter {private int[] imageresids;
  Public Banneraapter (int[] imageresids) {this.imageresids = Imageresids;
  @Override public int GetCount () {return imageresids.length * 10000 * 100;
  @Override public boolean isviewfromobject (view view, Object object) {return view = = object; @Override public Object Instantiateitem (viewgroup container, int position) {ImageView ImageView = new Imagevie
    W (Container.getcontext ());
    Position = position% Imageresids.length;
    Imageview.setbackgroundresource (Imageresids[position]);
    Container.addview (ImageView);
  return ImageView; @Override public void Destroyitem (ViewGroup container, int position, object object) {Container.removeview (Ima
  Geview) object);

 }
}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.