Android 사용자 정의 대기 대화 상자

16082 단어 Android대화 상자
최근 많은 앱 의 대기 대화 상 자 를 보고 자신의 것 이 너무 낮 다 는 것 을 알 게 되자 한 번 연구 한 끝 에 고심 끝 에 하 나 를 이 루 었 다.
  • Loading IndicatorView(extends View)클래스 를 사용자 정의 합 니 다
  • values/attrs.xml 를 작성 하고 스타일 블 과 item 등 태그 요 소 를 작성 합 니 다
  • 레이아웃 파일 에서 Loading IndicatorView 는 사용자 정의 속성 을 사용 합 니 다(namespace 주의)
  • Loading IndicatorView 의 구조 방법 에서 TypedArray 를 통 해 얻 을 수 있 습 니 다.
  • 설명 은 이것들 을 제공 합 니 다.다음은 코드 의 전시 입 니 다.매우 상세 합 니 다.
    1.사용자 정의 속성 성명 파일
    
    <declare-styleable name="AVLoadingIndicatorView"> 
        <attr name="indicator"> 
          <flag name="BallSpinFadeLoader" value="22"/> 
        </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     
      public static final int BallSpinFadeLoader=22; 
     
      @IntDef(flag = true, 
          value = { 
              BallSpinFadeLoader, 
          }) 
      public @interface Indicator{} 
     
      //Sizes (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(Context context) { 
        super(context); 
        init(null, 0); 
      } 
     
      public LoadingIndicatorView(Context context, AttributeSet attrs) { 
        super(context, attrs); 
        init(attrs, 0); 
      } 
     
      public LoadingIndicatorView(Context context, AttributeSet attrs, int defStyleAttr) { 
        super(context, attrs, defStyleAttr); 
        init(attrs, defStyleAttr); 
      } 
     
     
      @TargetApi(Build.VERSION_CODES.LOLLIPOP) 
      public LoadingIndicatorView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 
        super(context, attrs, defStyleAttr, defStyleRes); 
        init(attrs, defStyleAttr); 
      } 
     
      private void init(AttributeSet attrs, int defStyle) { 
        /** 
         *  TypedArray(     ) 
         */ 
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.AVLoadingIndicatorView); 
        mIndicatorId=a.getInt(R.styleable.AVLoadingIndicatorView_indicator, BallSpinFadeLoader);//       
        mIndicatorColor=a.getColor(R.styleable.AVLoadingIndicatorView_indicator_color, Color.WHITE);//       
        a.recycle();//        
        mPaint=new Paint(); 
        mPaint.setColor(mIndicatorColor);//        
        mPaint.setStyle(Paint.Style.FILL);//           
        mPaint.setAntiAlias(true);//    
        applyIndicator();// 
      } 
     
      private void applyIndicator(){ 
        switch (mIndicatorId){ 
          case BallSpinFadeLoader: 
            mIndicatorController=new BallSpinFadeLoaderIndicator(); 
            break; 
        } 
        mIndicatorController.setTarget(this);//        View 
      } 
     
      @Override 
      protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
        int width = measureDimension(dp2px(DEFAULT_SIZE), widthMeasureSpec);//  View    
        int height = measureDimension(dp2px(DEFAULT_SIZE), heightMeasureSpec);//  View    
        setMeasuredDimension(width, height);// 
      } 
     
      /** 
       *       
       * @param defaultSize      
       * @param measureSpec {@see widthMeasureSpec,heightMeasureSpec} 
       * @return         
       */ 
      private int measureDimension(int defaultSize,int measureSpec){ 
        int result = defaultSize; 
        int specMode = MeasureSpec.getMode(measureSpec);//     
        int specSize = MeasureSpec.getSize(measureSpec);//     
        if (specMode == MeasureSpec.EXACTLY) {//                ,              ,           
          result = specSize; 
        } else if (specMode == MeasureSpec.AT_MOST) {//                 
          result = Math.min(defaultSize, specSize);//     
        } 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.onLayout(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; 
      } 
     
      /** 
       *   View    
       * @return 
       */ 
      public int getWidth(){ 
        return mTarget.getWidth(); 
      } 
     
      /** 
       *   view    
       * @return 
       */ 
      public int getHeight(){ 
        return mTarget.getHeight(); 
      } 
     
      /** 
       *   view 
       */ 
      public void postInvalidate(){ 
        mTarget.postInvalidate(); 
      } 
     
      /** 
       * draw indicator what ever 
       * you want to draw 
       *   indicate 
       * @param canvas 
       * @param paint 
       */ 
      public abstract void draw(Canvas canvas,Paint paint); 
     
      /** 
       * create animation or animations 
       * ,and add to your indicator. 
       *           ,   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; 
      /** 
       *       
       */ 
      float[] scaleFloats=new float[]{SCALE, 
          SCALE, 
          SCALE, 
          SCALE, 
          SCALE, 
          SCALE, 
          SCALE, 
          SCALE}; 
      /** 
       *          
       */ 
      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(); 
        } 
      } 
     
      /** 
       *  O    (a,b),   R, A  X    α. 
       *  A    (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*(Math.cos(angle))); 
        float y= (float) (height/2+radius*(Math.sin(angle))); 
        return 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);//  ValueAnimator   
          scaleAnim.setDuration(1000);//          
          scaleAnim.setRepeatCount(-1);//         
          scaleAnim.setStartDelay(delays[i]);//       
          scaleAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {//ValueAnimator         ,                      
            @Override 
            public void onAnimationUpdate(ValueAnimator animation) { 
              scaleFloats[index] = (float) animation.getAnimatedValue();//        
              postInvalidate(); 
            } 
          }); 
          scaleAnim.start();//       
     
          ValueAnimator alphaAnim=ValueAnimator.ofInt(255, 77, 255);//      
          alphaAnim.setDuration(1000);// 
          alphaAnim.setRepeatCount(-1); 
          alphaAnim.setStartDelay(delays[i]); 
          alphaAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { 
            @Override 
            public void onAnimationUpdate(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; 
     
    /** 
     *        
     * @author    
     * @Date 2014-11-23 
     */ 
    public class UIHelper { 
       
      /**         */ 
      private static Dialog mLoadingDialog; 
       
       
      /** 
       *         
       * @param context     
       * @param msg         
       * @param cancelable           
       */ 
      public static void showDialogForLoading(Activity context, String msg, boolean cancelable) { 
        View view = LayoutInflater.from(context).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();    
      } 
       
      /** 
       *         
       */ 
      public static void hideDialogForLoading() { 
        if(mLoadingDialog != null && mLoadingDialog.isShowing()) { 
          mLoadingDialog.cancel(); 
        } 
      } 
     
    } 
    
    대화 상자 의 레이아웃:
    
    <?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"
        android:layout_height="wrap_content">
    
        <com.chni.lidong.androidtestdemo.loading.AVLoadingIndicatorView
          android: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="    …"
        android:textColor="@color/content"
        android:textSize="14sp" />
    
    </LinearLayout>
    
    
    대화 상자 의 스타일:
    
    <!--    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, "    ...", true); 
        Handler handler = new Handler(); 
        handler.postDelayed(new Runnable() { 
          @Override 
          public void run() { 
            UIHelper.hideDialogForLoading(); 
          } 
        },10000); 
      } 
     
    } 
    효과 도;

    이상 은 본문의 전체 내용 이 므 로 여러분 의 학습 에 도움 이 되 기 를 바 랍 니 다.

    좋은 웹페이지 즐겨찾기