Android Custom Wait dialog box _android

Source: Internet
Author: User

Recently, read a lot of app waiting dialog box, found their own too lower, so the study, and finally after painstaking efforts to achieve one.

    • Customizing a Loadingindicatorview (extends View) class
    • Write Values/attrs.xml, where you write tag elements such as styleable and item
    • Loadingindicatorview using custom attributes in Layout files (note namespace)
    • In the Loadingindicatorview construction method, the Typedarray is used to obtain

The description provides these, which is the display of the code, very detailed.
1, custom properties of the declaration file

<declare-styleable name= "Avloadingindicatorview" > 
    <attr name= "indicator" > 
      <flag name= " Ballspinfadeloader "value="/> </attr> <attr name= "Indicator_color" format= 
    "Color"/> 
  </declare-styleable> 


<pre name= "code" class= "HTML" >

Loadingindicatorview.java

Import Android.annotation.TargetApi; 
Import Android.content.Context; 
Import Android.content.res.TypedArray; 
Import Android.graphics.Canvas; 
Import Android.graphics.Color; 
Import Android.graphics.Paint; 
Import Android.os.Build; 
Import Android.support.annotation.IntDef; 
Import Android.util.AttributeSet; 
 
Import Android.view.View; 
 
 
Import COM.CHNI.LIDONG.ANDROIDTESTDEMO.R; /** * Created by Lidongon 2016/1/31 *. Ballspinfadeloader, * */public class Loadingindicatorview extends View {//indicators indicator public static fi 
 
  nal int ballspinfadeloader=22; @IntDef (flag = true, value = {ballspinfadeloader,}) public @interface indicator{}//siz 
 
  ES (with defaults in DP) public static final int default_size=45; 
  attrs int Mindicatorid; 
 
  int mindicatorcolor; 
 
  Paint Mpaint; 
 
  Baseindicatorcontroller Mindicatorcontroller; 
 
 
  Private Boolean mhasanimation; Public Loadingindicatorview { 
    Super (context); 
  init (null, 0); 
    Public Loadingindicatorview (context, AttributeSet attrs) {Super (context, attrs); 
  Init (attrs, 0); Loadingindicatorview (context, AttributeSet attrs, int defstyleattr) {Super (context, ATTRS, Def 
    STYLEATTR); 
  Init (attrs, defstyleattr); } @TargetApi (Build.version_codes. Lollipop) public Loadingindicatorview (context, AttributeSet attrs, int defstyleattr, int defstyleres) {su 
    Per (context, attrs, defstyleattr, defstyleres); 
  Init (attrs, defstyleattr); private void Init (AttributeSet attrs, int defstyle) {/** * get TypedArray (set of attributes)/TypedArray 
    A = GetContext (). Obtainstyledattributes (Attrs, R.styleable.avloadingindicatorview); Mindicatorid=a.getint (R.styleable.avloadingindicatorview_indicator, Ballspinfadeloader);//Get number attribute MIndicatorColor 
=a.getcolor (R.styleable.avloadingindicatorview_indicator_color, color.white);//Get Color properties    A.recycle ();//Collection of Properties Mpaint=new Paint (); Mpaint.setcolor (Mindicatorcolor);//Set the color Mpaint.setstyle (Paint.Style.FILL) of the brush;//Set the style of the brush to fill mpaint.setantialias (tr UE);//antialiasing Applyindicator ()//} private void Applyindicator () {switch (Mindicatorid) {case BALLSP 
        Infadeloader:mindicatorcontroller=new Ballspinfadeloaderindicator (); 
    Break Mindicatorcontroller.settarget (this);//sets the control to the current view} @Override protected void onmeasure (int Widthmeasur 
    espec, int heightmeasurespec) {int width = measuredimension (dp2px (default_size), widthmeasurespec);//Get the width of the view int height = measuredimension (dp2px (default_size), heightmeasurespec)//Get the height of the view setmeasureddimension (width, height //}/** * Measured dimension * @param defaultsize default size * @param measurespec {@see widthmeasurespec,heightmeasure SPEC} * @return Returns the result of the measurement * * private int measuredimension (int defaultsize,int measurespec) {int resUlt = defaultsize;  int specmode = Measurespec.getmode (MEASURESPEC);//measuring specification int specsize = measurespec.getsize (MEASURESPEC);//measuring size if (Specmode = = measurespec.exactly) 
    The {///parent control has set the size determined for the child control, the child control takes into account the size of the parent control, and how large it needs to be set = Specsize; 
    The else if (Specmode = = Measurespec.at_most) {//child control can set the specified size result = Math.min (DefaultSize, specsize) that it wishes;//Take the minimum value 
    else {result = DefaultSize; 
  return result; 
    } @Override protected void OnDraw (Canvas Canvas) {Super.ondraw (Canvas); 
  Drawindicator (canvas); @Override protected void OnLayout (Boolean changed, int left, int. top, int right, int bottom) {Super.onlayo 
    UT (changed, left, top, right, bottom); 
      if (!mhasanimation) {mhasanimation=true; 
    Applyanimation (); 
  } void Drawindicator (Canvas Canvas) {Mindicatorcontroller.draw (canvas,mpaint); 
  } void Applyanimation () {mindicatorcontroller.createanimation (); } private int dp2px (int dpvalue) {return (int) getcontext (). Getresources (). Getdisplaymetrics (). density * DPVALUE; 
 }

Baseindicatorcontroller.java

Package com.chni.lidong.androidtestdemo.loading; 
Import Android.graphics.Canvas; 
Import Android.graphics.Paint; 
 
Import Android.view.View; 
 
 
  /** * Created by Lidongon 2016/1/31/Public abstract class Baseindicatorcontroller {private View mtarget; 
  public void Settarget (View target) {this.mtarget=target; 
  Public View Gettarget () {return mtarget; 
  /** * Get View width * @return/public int getwidth () {return mtarget.getwidth (); 
  /** * Get the height of view * @return/public int getheight () {return mtarget.getheight (); 
  /** * Refresh view/public void Postinvalidate () {mtarget.postinvalidate (); 
   /** * Draw Indicator what ever * want to draw * Draw indicate * @param canvas * @param paint 
 
  * * Public abstract void Draw (Canvas canvas,paint Paint); 
   /** * Create animation or animations *, and add to your indicator. * Create animation or animation collection, add to INDCator * * Public abstract void createanimation (); 
 }

 ballspinfadeloaderindicator.java

Package com.chni.lidong.androidtestdemo.loading; 
Import Android.graphics.Canvas; 
 
Import Android.graphics.Paint; 
 
Import Com.nineoldandroids.animation.ValueAnimator; 
 
  /** * Created by Lidongon 2016/1/31/public class Ballspinfadeloaderindicator extends Baseindicatorcontroller { 
 
  public static final float scale=1.0f; 
  public static final int alpha=255; 
      /** * The proportion of dots * * * float[] scalefloats=new Float[]{scale, SCALE, SCALE, SCALE, SCALE, 
  SCALE, SCALE, SCALE}; 
      /** * DOT Transparency set * * int[] alphas=new Int[]{alpha, alpha, alpha, alpha, alpha, 
 
 
  Alpha, Alpha, alpha}; 
    @Override public void Draw (Canvas Canvas, Paint Paint) {float radius=getwidth ()/10; 
      for (int i = 0; i < 8; i++) {canvas.save (); 
      Point Point=circleat (GetWidth (), GetHeight (), GetWidth ()/2-radius,i* (MATH.PI/4)); 
     Canvas.translate (POINT.X,POINT.Y); Canvas.scale (Scalefloats[i],scalefloats[i]); 
      Paint.setalpha (Alphas[i]); 
      Canvas.drawcircle (0,0,radius,paint); 
    Canvas.restore (); 
   The center of the/** * Circle O is (a,b), the radius is r, and point A is the angle α to the x axis. 
   * The coordinates of point A are (a+r*cosα,b+r*sinα) * @param width * @param height * @param radius * @param angle * @return * * Point circleat (int width,int height,float radius,double angle) {float x= (float) (width/2+radius* ( 
    GLE))); 
    float y= (float) (height/2+radius* (Math.sin (angle))); 
  Return to New Point (x,y); 
    @Override public void Createanimation () {int[] delays= {0, 120, 240, 360, 480, 600, 720, 780, 840}; 
      for (int i = 0; i < 8; i++) {final int index=i; Valueanimator scaleanim=valueanimator.offloat (1,0.4f,1);//Create Valueanimator Object Scaleanim.setduration (1000); Sets the duration of the animation Scaleanim.setrepeatcount (-1);//Set whether the animation repeats Scaleanim.setstartdelay (Delays[i]);/delayed start animation Scalean Im.addupdatelistener (New VaLueanimator.animatorupdatelistener () {//valueanimator is responsible for first-time content, so it must be monitored to implement updates to the object's associated properties @Override public vo ID onanimationupdate (valueanimator animation) {Scalefloats[index] = (float) animation.getanimatedvalue ()//Get when 
        The value of the front frame postinvalidate (); 
      } 
      }); Scaleanim.start ()//Start Properties Animation Valueanimator Alphaanim=valueanimator.ofint (255, 77, 255);/Transparency Animation Alphaanim.set 
      Duration (1000);//Alphaanim.setrepeatcount (-1); 
      Alphaanim.setstartdelay (Delays[i]); Alphaanim.addupdatelistener (New Valueanimator.animatorupdatelistener () {@Override public void Onanimati 
          OnUpdate (Valueanimator animation) {Alphas[index] = (int) animation.getanimatedvalue (); 
        Postinvalidate (); 
      } 
      }); 
    Alphaanim.start (); 
    } Final class point{public float x; 
 
    public float y; 
      Public point (float x, float y) {this.x=x; 
    This.y=y; 
 
 
} 
  }} 
 

Uihelp.java

Package com.chni.lidong.androidtestdemo.utils; 
Import android.app.Activity; 
Import Android.app.Dialog; 
Import Android.view.LayoutInflater; 
Import Android.view.View; 
Import Android.widget.LinearLayout; 
 
Import Android.widget.TextView; 
 
Import COM.CHNI.LIDONG.ANDROIDTESTDEMO.R; /** * dialog Box Implementation * @author Lidong * @Date 2014-11-23/public class Uihelper {/** Load Data dialog box * * private static D 
   
   
  Ialog Mloadingdialog; /** * Display Load dialog box * @param context * @param msg dialog box display content * @param cancelable dialog box can be canceled/public STA TIC void showdialogforloading (activity context, String msg, Boolean cancelable) {View view = Layoutinflater.from (con 
    Text). Inflate (r.layout.layout_loading_dialog, NULL); 
    TextView Loadingtext = (TextView) View.findviewbyid (R.id.id_tv_loading_dialog_text); 
     
    Loadingtext.settext (msg); 
    Mloadingdialog = new Dialog (context, r.style.loading_dialog_style); 
    Mloadingdialog.setcancelable (cancelable); MloadinGdialog.setcontentview (view, New Linearlayout.layoutparams (LinearLayout.LayoutParams.MATCH_PARENT, 
    LinearLayout.LayoutParams.MATCH_PARENT));    
  Mloadingdialog.show ();  /** * Close Load dialog box/public static void Hidedialogforloading () {if (Mloadingdialog!= null && 
    Mloadingdialog.isshowing ()) {mloadingdialog.cancel (); 
 } 
  } 
 
}

Layout of dialog boxes:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/" Android "xmlns:app=" Http://schemas.android.com/apk/res-auto "android:layout_width=" Wrap_content "Android:layout_ height= "Wrap_content" android:background= "@drawable/bg_loading_dialog_shape" android:gravity= "Center" android:

  minheight= "60DP" android:minwidth= "180DP" android:orientation= "vertical" android:padding= "@dimen/padding_10" > <linearlayout android:layout_width= "Wrap_content" android:layout_weight= "1" android:gravity= "center" a ndroid:layout_height= "Wrap_content" > <com.chni.lidong.androidtestdemo.loading.avloadingindicatorview andr
      Oid:layout_width= "Wrap_content" android:layout_height= "wrap_content" app:indicator= "BallSpinFadeLoader" App:indicator_color= "@color/green"/> </LinearLayout> <textview android:id= "@+id/id_tv_loading _dialog_text "Android:layout_width=" WraP_content "android:layout_height=" wrap_content "android:layout_margintop=" @dimen/padding_5 "android:text=" is logged in

 ... "android:textcolor=" @color/content "android:textsize=" 14sp "/> </LinearLayout>

Style of dialog box:

<!--custom loading Dialog--> <style name= "Loading_dialog_style"
parent= "@android: Style/theme.dialog" >
  <item name= "Android:windowframe" > @null </item>
  <item name= "Android:windownotitle" >true </item>
  <item name= "Android:windowbackground" > @color/transparent</item>
  <item name= "Android:windowisfloating" >true</item>
  <item name= "Android:windowcontentoverlay" > @null </ Item>
</style>

Mainactivity.java

public class Main7activity extends Appcompatactivity { 
 
  @Override 
  protected void OnCreate (Bundle Savedinstancestate) { 
    super.oncreate (savedinstancestate); 
    Setcontentview (r.layout.activity_main7); 
    Toolbar Toolbar = (Toolbar) Findviewbyid (R.id.toolbar); 
    Setsupportactionbar (toolbar); 
 
    Floatingactionbutton fab = (Floatingactionbutton) Findviewbyid (r.id.fab); 
    Fab.setonclicklistener (New View.onclicklistener () { 
      @Override public 
      void OnClick (view view) { 
        Snackbar.make (View, "Replace with your own action", Snackbar.length_long) 
            . Setaction ("action", null). Show (); 
    }); 
    Uihelper.showdialogforloading (This, "Loading ...", true); 
    Handler Handler = new Handler (); 
    Handler.postdelayed (New Runnable () { 
      @Override public 
      void Run () { 
        uihelper.hidedialogforloading (); 
      } 
    },10000); 
  } 
 

Effect chart;

The above is the entire content of this article, I hope to help you learn.

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.