在 Android 中实现类似于 iOS 的旋转活动指示器

发布于 2024-12-02 01:15:54 字数 1147 浏览 1 评论 0原文

我正在尝试实现类似于我在 Android 中放置的旋转活动。我相信我应该使用 ProgressDialog。我的问题源于如何实际操作 ProgressDialog 以使其看起来像活动指示器。

欢迎任何想法。一个例子的链接就更好了。

谢谢。 在此处输入图像描述

REEDIT:

myProgress.java

public class myProgress extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ProgressDialog d = (ProgressDialog)findViewById(R.id.progres);

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/progres"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
>
<ProgressBar  
    android:id="@+id/progressBar"
    android:indeterminate="true" 
    style="?android:attr/progressBarStyleLarge"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true" 
/>
</RelativeLayout>

I am trying to implement the spinning activity similar to the the one I have placed below in Android. I believe I should use the ProgressDialog. My issue arises from how to actually manipulate the ProgressDialog to appear like the activity indicator.

Any thoughts are welcome. A link to an example would even be better.

Thanks.
enter image description here

REEDIT:

myProgress.java

public class myProgress extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ProgressDialog d = (ProgressDialog)findViewById(R.id.progres);

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/progres"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
>
<ProgressBar  
    android:id="@+id/progressBar"
    android:indeterminate="true" 
    style="?android:attr/progressBarStyleLarge"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true" 
/>
</RelativeLayout>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

悸初 2024-12-09 01:15:54

我编写了自己的自定义 LoadingIndicatorView。

它由两个文件组成:

  • LoadingIndicatorBarView
  • LoadingIndicatorView

优点

  • 以编程方式创建,没有 PNG 滑稽动作,意味着可扩展且清晰:D
  • 可自定义条形颜色和角半径(如果您理解我的代码)

缺点 :

  • 性能不如 iOS 版本(我只是一个来自 iOS 背景的初学者 Android 开发者,你期望什么?) :P

免责声明

  • 如果你的项目不要怪我爆炸了,我把它作为免费的公共领域代码。

您会注意到我的编码风格和结构与我的 iOS 编程代码非常相似。我以编程方式完成所有事情,如果可以的话,就不使用 XML。

如何使用这个 Loading Indicator

将所有三个类的源代码复制并粘贴到其 Java 文件中后,您想要使用 LoadingIndicatorView 类,您不需要接触其他类,除非您想要自定义每个条形的颜色或圆角。

在您的 Activity 中创建一个 LoadingIndicatorView 实例:

import com.companyName.myApplication.views.LoadingIndicatorView;

public class MyActivity extends AppCompatActivity
{
    public mainLayout RelativeLayout;
    ...
    public LoadingIndicatorView loadingIndicator;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        initViews();
        initLayouts();
        addViews();
    }

    public void initViews()
    {
        mainLayout = new RelativeLayout(this);
        mainLayout.setBackgroundColor(Color.BLACK);

        ...

        // ---------------------------------------------------
        // 40 here is the radius of the circle
        // try and use multiples of 2, e.g. 40, 60, 80 etc
        // ---------------------------------------------------
        loadingIndicator = new LoadingIndicatorView(this, 40);

        // hide until ready to start animating
        loadingIndicator.setAlpha(0.0f);
    }

    public void initLayouts()
    {
        ...

        // Need API level 17 for this, set in your AndroidManifeset.xml
        mainLayout.setId(View.generateViewId());
        loadingIndicator.setId(View.generateViewId());

        RelativeLayout.LayoutParams loadingIndicatorLayoutParams = new RelativeLayout.LayoutParams(
                (int)(loadingIndicator.radius * 2.0f),
                (int)(loadingIndicator.radius * 2.0f)
        );

        loadingIndicatorLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);

        loadingIndicator.setLayoutParams(loadingIndicatorLayoutParams);
    }

    public void addViews()
    {
        ...

        mainLayout.addView(loadingIndicator);

        setContentView(mainLayout);
    }
}

一旦您准备好显示它(例如在按钮单击侦听器中),则您可以调用:

loadingIndicator.startAnimating();

当您想要停止并隐藏指示器时,请调用:

loadingIndicator.stopAnimating();

你最终会得到这样的结果:

加载指示器屏幕截图

LoadingIndicatorView.java

package com.companyName.myApplication.views;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.animation.RotateAnimation;
import android.widget.RelativeLayout;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Zhang on 11/02/16.
 */
public class LoadingIndicatorView extends RelativeLayout
{
    private Context context;

    private int numberOfBars;

    public ArrayList<LoadingIndicatorBarView> arrBars;

    public float radius;

    private boolean isAnimating;
    private int currentFrame;

    private final Handler handler = new Handler();
    private Runnable playFrameRunnable;

    public LoadingIndicatorView(Context context, float radius)
    {
        super(context);

        this.context = context;
        this.radius = radius;
        this.numberOfBars = 12;

        initViews();
        initLayouts();
        addViews();
        spreadBars();
    }

    public void initViews()
    {
        arrBars = new ArrayList<LoadingIndicatorBarView>();

        for(int i = 0; i < numberOfBars; i++)
        {
            LoadingIndicatorBarView bar = new LoadingIndicatorBarView(context, radius / 10.0f);

            arrBars.add(bar);
        }
    }

    public void initLayouts()
    {
        for(int i = 0; i < numberOfBars; i++)
        {
            LoadingIndicatorBarView bar = arrBars.get(i);

            bar.setId(View.generateViewId());

            RelativeLayout.LayoutParams barLayoutParams = new RelativeLayout.LayoutParams(
                    (int)(radius / 5.0f),
                    (int)(radius / 2.0f)
            );

            barLayoutParams.addRule(ALIGN_PARENT_TOP);
            barLayoutParams.addRule(CENTER_HORIZONTAL);

            bar.setLayoutParams(barLayoutParams);
        }
    }

    public void addViews()
    {
        for(int i = 0; i < numberOfBars; i++)
        {
            LoadingIndicatorBarView bar = arrBars.get(i);

            addView(bar);
        }
    }

    public void spreadBars()
    {
        int degrees = 0;

        for(int i = 0; i < arrBars.size(); i++)
        {
            LoadingIndicatorBarView bar = arrBars.get(i);

            rotateBar(bar, degrees);

            degrees += 30;
        }
    }

    private void rotateBar(LoadingIndicatorBarView bar, float degrees)
    {
        RotateAnimation animation = new RotateAnimation(0, degrees, radius / 10.0f, radius);
        animation.setDuration(0);
        animation.setFillAfter(true);

        bar.setAnimation(animation);
        animation.start();
    }

    public void startAnimating()
    {
        setAlpha(1.0f);

        isAnimating = true;

        playFrameRunnable = new Runnable()
        {
            @Override
            public void run()
            {
                playFrame();
            }
        };

        // recursive function until isAnimating is false
        playFrame();
    }

    public void stopAnimating()
    {
        isAnimating = false;

        setAlpha(0.0f);

        invalidate();

        playFrameRunnable = null;
    }

    private void playFrame()
    {
        if(isAnimating)
        {
            resetAllBarAlpha();
            updateFrame();

            handler.postDelayed(playFrameRunnable, 0);
        }
    }

    private void updateFrame()
    {
        if (isAnimating)
        {
            showFrame(currentFrame);
            currentFrame += 1;

            if (currentFrame > 11)
            {
                currentFrame = 0;
            }
        }
    }

    private void resetAllBarAlpha()
    {
        LoadingIndicatorBarView bar = null;

        for (int i = 0; i < arrBars.size(); i++)
        {
            bar = arrBars.get(i);

            bar.setAlpha(0.5f);
        }
    }

    private void showFrame(int frameNumber)
    {
        int[] indexes = getFrameIndexesForFrameNumber(frameNumber);

        gradientColorBarSets(indexes);
    }

    private int[] getFrameIndexesForFrameNumber(int frameNumber)
    {
        if(frameNumber == 0)
        {
            return indexesFromNumbers(0, 11, 10, 9);
        }
        else if(frameNumber == 1)
        {
            return indexesFromNumbers(1, 0, 11, 10);
        }
        else if(frameNumber == 2)
        {
            return indexesFromNumbers(2, 1, 0, 11);
        }
        else if(frameNumber == 3)
        {
            return indexesFromNumbers(3, 2, 1, 0);
        }
        else if(frameNumber == 4)
        {
            return indexesFromNumbers(4, 3, 2, 1);
        }
        else if(frameNumber == 5)
        {
            return indexesFromNumbers(5, 4, 3, 2);
        }
        else if(frameNumber == 6)
        {
            return indexesFromNumbers(6, 5, 4, 3);
        }
        else if(frameNumber == 7)
        {
            return indexesFromNumbers(7, 6, 5, 4);
        }
        else if(frameNumber == 8)
        {
            return indexesFromNumbers(8, 7, 6, 5);
        }
        else if(frameNumber == 9)
        {
            return indexesFromNumbers(9, 8, 7, 6);
        }
        else if(frameNumber == 10)
        {
            return indexesFromNumbers(10, 9, 8, 7);
        }
        else
        {
            return indexesFromNumbers(11, 10, 9, 8);
        }
    }

    private int[] indexesFromNumbers(int i1, int i2, int i3, int i4)
    {
        int[] indexes = {i1, i2, i3, i4};
        return indexes;
    }

    private void gradientColorBarSets(int[] indexes)
    {
        float alpha = 1.0f;

        LoadingIndicatorBarView barView = null;

        for(int i = 0; i < indexes.length; i++)
        {
            int barIndex = indexes[i];

            barView = arrBars.get(barIndex);


            barView.setAlpha(alpha);
            alpha -= 0.125f;
        }

        invalidate();
    }
}

LoadingIndicatorBarView.java

package com.companyName.myApplication.views;

import android.content.Context;
import android.graphics.Color;
import android.widget.RelativeLayout;

import com.companyName.myApplication.helper_classes.ToolBox;

/**
 * Created by Zhang on 11/02/16.
 */
public class LoadingIndicatorBarView extends RelativeLayout
{
    private Context context;
    private float cornerRadius;

    public LoadingIndicatorBarView(Context context, float cornerRadius)
    {
        super(context);

        this.context = context;
        this.cornerRadius = cornerRadius;

        initViews();
    }

    public void initViews()
    {
        setBackground(ToolBox.roundedCornerRectWithColor(
                Color.argb(255, 255, 255, 255), cornerRadius));

        setAlpha(0.5f);
    }

    public void resetColor()
    {
        setBackground(ToolBox.roundedCornerRectWithColor(
                Color.argb(255, 255, 255, 255), cornerRadius));

        setAlpha(0.5f);
    }
}

Toolbox.java

package com.companyName.myApplication.helper_classes;

import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Paint;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;

/**
 * Created by Zhang on 3/02/16.
 */
public class ToolBox
{
    private static ToolBox instance;
    public Context context;

    private ToolBox()
    {

    }

    public synchronized static ToolBox getInstance()
    {
        if(instance == null)
        {
            instance = new ToolBox();
        }

        return instance;
    }

    public static ShapeDrawable roundedCornerRectOutlineWithColor(int color, float cornerRadius,
                                                                  float strokeWidth)
    {
        float[] radii = new float[] {
                cornerRadius, cornerRadius,
                cornerRadius, cornerRadius,
                cornerRadius, cornerRadius,
                cornerRadius, cornerRadius
        };

        RoundRectShape roundedCornerShape = new RoundRectShape(radii, null, null);

        ShapeDrawable shape = new ShapeDrawable();
        shape.getPaint().setColor(color);
        shape.setShape(roundedCornerShape);
        shape.getPaint().setStrokeWidth(strokeWidth);
        shape.getPaint().setStyle(Paint.Style.STROKE);

        return shape;
    }

    public static ShapeDrawable roundedCornerRectWithColor(int color, float cornerRadius)
    {
        float[] radii = new float[] {
                cornerRadius, cornerRadius,
                cornerRadius, cornerRadius,
                cornerRadius, cornerRadius,
                cornerRadius, cornerRadius
        };

        RoundRectShape roundedCornerShape = new RoundRectShape(radii, null, null);

        ShapeDrawable shape = new ShapeDrawable();
        shape.getPaint().setColor(color);
        shape.setShape(roundedCornerShape);

        return shape;
    }

    public static ShapeDrawable roundedCornerRectWithColor(int color, float topLeftRadius, float
            topRightRadius, float bottomRightRadius, float bottomLeftRadius)
    {
        float[] radii = new float[] {
                topLeftRadius, topLeftRadius,
                topRightRadius, topRightRadius,
                bottomRightRadius, bottomRightRadius,
                bottomLeftRadius, bottomLeftRadius
        };

        RoundRectShape roundedCornerShape = new RoundRectShape(radii, null, null);

        ShapeDrawable shape = new ShapeDrawable();
        shape.getPaint().setColor(color);
        shape.setShape(roundedCornerShape);

        return shape;
    }

    public static int getScreenWidth()
    {
        return Resources.getSystem().getDisplayMetrics().widthPixels;
    }

    public static int getScreenHeight()
    {
        return Resources.getSystem().getDisplayMetrics().heightPixels;
    }

    public static int getScreenOrientation(Context context)
    {
        return context.getResources().getConfiguration().orientation;
    }

    public static boolean isLandscapeOrientation(Context context)
    {
        return getScreenOrientation(context) == Configuration.ORIENTATION_LANDSCAPE;
    }

}

这个 Toolbox 类是我的方便帮助程序类,用于在我的所有项目中创建圆角形状等。

希望有帮助:D

I wrote my own custom LoadingIndicatorView.

It consists of two files:

  • LoadingIndicatorBarView
  • LoadingIndicatorView

Pros:

  • Programmatically created, no PNG antics meaning scalable and crisp :D
  • Customizable bar colors and corner radius (if you understand my code)

Cons:

  • Not as performant as the iOS version (I'm just a beginner Android developer coming from iOS background, what do you expect?) :P

Disclaimer:

  • Don't blame me if your project blows up, I'm putting this as free public domain code.

You'll notice my coding style and structure resemble my iOS programming codes a lot. I do everything programmatically, no XML if I can get away with it.

How to use this Loading Indicator

After you've copied and pasted all three class source codes into their Java file, you want to use the LoadingIndicatorView class, you shouldn't need to touch the other class, unless you want to customise the colour or rounded corner of each bar.

Create an instance of LoadingIndicatorView like this in your Activity:

import com.companyName.myApplication.views.LoadingIndicatorView;

public class MyActivity extends AppCompatActivity
{
    public mainLayout RelativeLayout;
    ...
    public LoadingIndicatorView loadingIndicator;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        initViews();
        initLayouts();
        addViews();
    }

    public void initViews()
    {
        mainLayout = new RelativeLayout(this);
        mainLayout.setBackgroundColor(Color.BLACK);

        ...

        // ---------------------------------------------------
        // 40 here is the radius of the circle
        // try and use multiples of 2, e.g. 40, 60, 80 etc
        // ---------------------------------------------------
        loadingIndicator = new LoadingIndicatorView(this, 40);

        // hide until ready to start animating
        loadingIndicator.setAlpha(0.0f);
    }

    public void initLayouts()
    {
        ...

        // Need API level 17 for this, set in your AndroidManifeset.xml
        mainLayout.setId(View.generateViewId());
        loadingIndicator.setId(View.generateViewId());

        RelativeLayout.LayoutParams loadingIndicatorLayoutParams = new RelativeLayout.LayoutParams(
                (int)(loadingIndicator.radius * 2.0f),
                (int)(loadingIndicator.radius * 2.0f)
        );

        loadingIndicatorLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);

        loadingIndicator.setLayoutParams(loadingIndicatorLayoutParams);
    }

    public void addViews()
    {
        ...

        mainLayout.addView(loadingIndicator);

        setContentView(mainLayout);
    }
}

Once you're ready to show it, e.g. in a button click listener, then you call:

loadingIndicator.startAnimating();

When you want to stop and hide the indicator, call:

loadingIndicator.stopAnimating();

You end up with something like this:

loading indicator screenshot

LoadingIndicatorView.java

package com.companyName.myApplication.views;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.animation.RotateAnimation;
import android.widget.RelativeLayout;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Zhang on 11/02/16.
 */
public class LoadingIndicatorView extends RelativeLayout
{
    private Context context;

    private int numberOfBars;

    public ArrayList<LoadingIndicatorBarView> arrBars;

    public float radius;

    private boolean isAnimating;
    private int currentFrame;

    private final Handler handler = new Handler();
    private Runnable playFrameRunnable;

    public LoadingIndicatorView(Context context, float radius)
    {
        super(context);

        this.context = context;
        this.radius = radius;
        this.numberOfBars = 12;

        initViews();
        initLayouts();
        addViews();
        spreadBars();
    }

    public void initViews()
    {
        arrBars = new ArrayList<LoadingIndicatorBarView>();

        for(int i = 0; i < numberOfBars; i++)
        {
            LoadingIndicatorBarView bar = new LoadingIndicatorBarView(context, radius / 10.0f);

            arrBars.add(bar);
        }
    }

    public void initLayouts()
    {
        for(int i = 0; i < numberOfBars; i++)
        {
            LoadingIndicatorBarView bar = arrBars.get(i);

            bar.setId(View.generateViewId());

            RelativeLayout.LayoutParams barLayoutParams = new RelativeLayout.LayoutParams(
                    (int)(radius / 5.0f),
                    (int)(radius / 2.0f)
            );

            barLayoutParams.addRule(ALIGN_PARENT_TOP);
            barLayoutParams.addRule(CENTER_HORIZONTAL);

            bar.setLayoutParams(barLayoutParams);
        }
    }

    public void addViews()
    {
        for(int i = 0; i < numberOfBars; i++)
        {
            LoadingIndicatorBarView bar = arrBars.get(i);

            addView(bar);
        }
    }

    public void spreadBars()
    {
        int degrees = 0;

        for(int i = 0; i < arrBars.size(); i++)
        {
            LoadingIndicatorBarView bar = arrBars.get(i);

            rotateBar(bar, degrees);

            degrees += 30;
        }
    }

    private void rotateBar(LoadingIndicatorBarView bar, float degrees)
    {
        RotateAnimation animation = new RotateAnimation(0, degrees, radius / 10.0f, radius);
        animation.setDuration(0);
        animation.setFillAfter(true);

        bar.setAnimation(animation);
        animation.start();
    }

    public void startAnimating()
    {
        setAlpha(1.0f);

        isAnimating = true;

        playFrameRunnable = new Runnable()
        {
            @Override
            public void run()
            {
                playFrame();
            }
        };

        // recursive function until isAnimating is false
        playFrame();
    }

    public void stopAnimating()
    {
        isAnimating = false;

        setAlpha(0.0f);

        invalidate();

        playFrameRunnable = null;
    }

    private void playFrame()
    {
        if(isAnimating)
        {
            resetAllBarAlpha();
            updateFrame();

            handler.postDelayed(playFrameRunnable, 0);
        }
    }

    private void updateFrame()
    {
        if (isAnimating)
        {
            showFrame(currentFrame);
            currentFrame += 1;

            if (currentFrame > 11)
            {
                currentFrame = 0;
            }
        }
    }

    private void resetAllBarAlpha()
    {
        LoadingIndicatorBarView bar = null;

        for (int i = 0; i < arrBars.size(); i++)
        {
            bar = arrBars.get(i);

            bar.setAlpha(0.5f);
        }
    }

    private void showFrame(int frameNumber)
    {
        int[] indexes = getFrameIndexesForFrameNumber(frameNumber);

        gradientColorBarSets(indexes);
    }

    private int[] getFrameIndexesForFrameNumber(int frameNumber)
    {
        if(frameNumber == 0)
        {
            return indexesFromNumbers(0, 11, 10, 9);
        }
        else if(frameNumber == 1)
        {
            return indexesFromNumbers(1, 0, 11, 10);
        }
        else if(frameNumber == 2)
        {
            return indexesFromNumbers(2, 1, 0, 11);
        }
        else if(frameNumber == 3)
        {
            return indexesFromNumbers(3, 2, 1, 0);
        }
        else if(frameNumber == 4)
        {
            return indexesFromNumbers(4, 3, 2, 1);
        }
        else if(frameNumber == 5)
        {
            return indexesFromNumbers(5, 4, 3, 2);
        }
        else if(frameNumber == 6)
        {
            return indexesFromNumbers(6, 5, 4, 3);
        }
        else if(frameNumber == 7)
        {
            return indexesFromNumbers(7, 6, 5, 4);
        }
        else if(frameNumber == 8)
        {
            return indexesFromNumbers(8, 7, 6, 5);
        }
        else if(frameNumber == 9)
        {
            return indexesFromNumbers(9, 8, 7, 6);
        }
        else if(frameNumber == 10)
        {
            return indexesFromNumbers(10, 9, 8, 7);
        }
        else
        {
            return indexesFromNumbers(11, 10, 9, 8);
        }
    }

    private int[] indexesFromNumbers(int i1, int i2, int i3, int i4)
    {
        int[] indexes = {i1, i2, i3, i4};
        return indexes;
    }

    private void gradientColorBarSets(int[] indexes)
    {
        float alpha = 1.0f;

        LoadingIndicatorBarView barView = null;

        for(int i = 0; i < indexes.length; i++)
        {
            int barIndex = indexes[i];

            barView = arrBars.get(barIndex);


            barView.setAlpha(alpha);
            alpha -= 0.125f;
        }

        invalidate();
    }
}

LoadingIndicatorBarView.java

package com.companyName.myApplication.views;

import android.content.Context;
import android.graphics.Color;
import android.widget.RelativeLayout;

import com.companyName.myApplication.helper_classes.ToolBox;

/**
 * Created by Zhang on 11/02/16.
 */
public class LoadingIndicatorBarView extends RelativeLayout
{
    private Context context;
    private float cornerRadius;

    public LoadingIndicatorBarView(Context context, float cornerRadius)
    {
        super(context);

        this.context = context;
        this.cornerRadius = cornerRadius;

        initViews();
    }

    public void initViews()
    {
        setBackground(ToolBox.roundedCornerRectWithColor(
                Color.argb(255, 255, 255, 255), cornerRadius));

        setAlpha(0.5f);
    }

    public void resetColor()
    {
        setBackground(ToolBox.roundedCornerRectWithColor(
                Color.argb(255, 255, 255, 255), cornerRadius));

        setAlpha(0.5f);
    }
}

Toolbox.java

package com.companyName.myApplication.helper_classes;

import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Paint;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;

/**
 * Created by Zhang on 3/02/16.
 */
public class ToolBox
{
    private static ToolBox instance;
    public Context context;

    private ToolBox()
    {

    }

    public synchronized static ToolBox getInstance()
    {
        if(instance == null)
        {
            instance = new ToolBox();
        }

        return instance;
    }

    public static ShapeDrawable roundedCornerRectOutlineWithColor(int color, float cornerRadius,
                                                                  float strokeWidth)
    {
        float[] radii = new float[] {
                cornerRadius, cornerRadius,
                cornerRadius, cornerRadius,
                cornerRadius, cornerRadius,
                cornerRadius, cornerRadius
        };

        RoundRectShape roundedCornerShape = new RoundRectShape(radii, null, null);

        ShapeDrawable shape = new ShapeDrawable();
        shape.getPaint().setColor(color);
        shape.setShape(roundedCornerShape);
        shape.getPaint().setStrokeWidth(strokeWidth);
        shape.getPaint().setStyle(Paint.Style.STROKE);

        return shape;
    }

    public static ShapeDrawable roundedCornerRectWithColor(int color, float cornerRadius)
    {
        float[] radii = new float[] {
                cornerRadius, cornerRadius,
                cornerRadius, cornerRadius,
                cornerRadius, cornerRadius,
                cornerRadius, cornerRadius
        };

        RoundRectShape roundedCornerShape = new RoundRectShape(radii, null, null);

        ShapeDrawable shape = new ShapeDrawable();
        shape.getPaint().setColor(color);
        shape.setShape(roundedCornerShape);

        return shape;
    }

    public static ShapeDrawable roundedCornerRectWithColor(int color, float topLeftRadius, float
            topRightRadius, float bottomRightRadius, float bottomLeftRadius)
    {
        float[] radii = new float[] {
                topLeftRadius, topLeftRadius,
                topRightRadius, topRightRadius,
                bottomRightRadius, bottomRightRadius,
                bottomLeftRadius, bottomLeftRadius
        };

        RoundRectShape roundedCornerShape = new RoundRectShape(radii, null, null);

        ShapeDrawable shape = new ShapeDrawable();
        shape.getPaint().setColor(color);
        shape.setShape(roundedCornerShape);

        return shape;
    }

    public static int getScreenWidth()
    {
        return Resources.getSystem().getDisplayMetrics().widthPixels;
    }

    public static int getScreenHeight()
    {
        return Resources.getSystem().getDisplayMetrics().heightPixels;
    }

    public static int getScreenOrientation(Context context)
    {
        return context.getResources().getConfiguration().orientation;
    }

    public static boolean isLandscapeOrientation(Context context)
    {
        return getScreenOrientation(context) == Configuration.ORIENTATION_LANDSCAPE;
    }

}

This Toolbox class is my convenience helper class to create rounded corner shapes etc in all my projects.

Hope that helps :D

伴随着你 2024-12-09 01:15:54

这就是我实现它的方法,

这里的代码

@Override   
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_LOADING:
        final Dialog dialog = new Dialog(this, android.R.style.Theme_Translucent);          
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.loading);
        dialog.setCancelable(true);
        dialog.setOnCancelListener(new OnCancelListener() {             
            @Override
            public void onCancel(DialogInterface dialog) {
                //onBackPressed();
            }
        });
    return dialog;  

    default:
        return null;
    }
};

loading.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/progres"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
>
<ProgressBar  
    android:indeterminate="true" 
    style="?android:attr/progressBarStyleLarge"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true" 
/> 
</RelativeLayout>

调用对话框,并

showDialog(DIALOG_LOADING);

隐藏它

dismissDialog(DIALOG_LOADING);

使用UPDATE

,如果您愿意,自定义指示器您可以在中执行以下操作layout.xml

  1. ProgressBar 替换为 ImageView
  2. 将 ImageView 的 background 设置为 AnimationDrawable
  3. 你可以在onPrepareDialog中启动动画

this is how i achieve it

here is the code

@Override   
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_LOADING:
        final Dialog dialog = new Dialog(this, android.R.style.Theme_Translucent);          
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.loading);
        dialog.setCancelable(true);
        dialog.setOnCancelListener(new OnCancelListener() {             
            @Override
            public void onCancel(DialogInterface dialog) {
                //onBackPressed();
            }
        });
    return dialog;  

    default:
        return null;
    }
};

here is the loading.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/progres"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
>
<ProgressBar  
    android:indeterminate="true" 
    style="?android:attr/progressBarStyleLarge"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true" 
/> 
</RelativeLayout>

call the dialog with

showDialog(DIALOG_LOADING);

hide it using

dismissDialog(DIALOG_LOADING);

UPDATE

if you want and custom indicator you can do the following in the layout.xml.

  1. replace the ProgressBar with an ImageView
  2. set the background of the ImageView to a AnimationDrawable
  3. you can start the animation in onPrepareDialog
桃气十足 2024-12-09 01:15:54

我相信你正在寻找进步对话框。您可以通过此链接开始设置。

http://www.helloandroid.com/tutorials/using-threads-and-progressdialog

 pd = ProgressDialog.show(this, "Working..", "Calculating Pi", true,
                                false);
private Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                        pd.dismiss();
                        tv.setText(pi_string);

                }
        };

You are looking for progressDialog i believe. This link can you set you start with it.

http://www.helloandroid.com/tutorials/using-threads-and-progressdialog

 pd = ProgressDialog.show(this, "Working..", "Calculating Pi", true,
                                false);
private Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                        pd.dismiss();
                        tv.setText(pi_string);

                }
        };
指尖凝香 2024-12-09 01:15:54

看看这个图书馆就知道了。 IOSDialog/Spinner 库

它非常易于使用并解决您的问题。有了它,您可以像在 IOS 中一样轻松创建和使用 Spinner。
代码示例:

final IOSDialog dialog1 = new IOSDialog.Builder(IOSDialogActivity.this)
            .setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    dialog0.show();
                }
            })
            .setDimAmount(3)
            .setSpinnerColorRes(R.color.colorGreen)
            .setMessageColorRes(R.color.colorAccent)
            .setTitle(R.string.standard_title)
            .setTitleColorRes(R.color.colorPrimary)
            .setMessageContent("My message")
            .setCancelable(true)
            .setMessageContentGravity(Gravity.END)
            .build();

结果

 final IOSDialog dialog0 = new IOSDialog.Builder(IOSDialogActivity.this)
            .setTitle("Default IOS bar")
            .setTitleColorRes(R.color.gray)
            .build();

结果:标准 IOS 对话框

Just look at this library. IOSDialog/Spinner library

It is very easy to use and solves your problem. With it, you can easily create and use spinner like in IOS.
The example of code:

final IOSDialog dialog1 = new IOSDialog.Builder(IOSDialogActivity.this)
            .setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    dialog0.show();
                }
            })
            .setDimAmount(3)
            .setSpinnerColorRes(R.color.colorGreen)
            .setMessageColorRes(R.color.colorAccent)
            .setTitle(R.string.standard_title)
            .setTitleColorRes(R.color.colorPrimary)
            .setMessageContent("My message")
            .setCancelable(true)
            .setMessageContentGravity(Gravity.END)
            .build();

Result

 final IOSDialog dialog0 = new IOSDialog.Builder(IOSDialogActivity.this)
            .setTitle("Default IOS bar")
            .setTitleColorRes(R.color.gray)
            .build();

Result: stadard IOS Dialog

离旧人 2024-12-09 01:15:54

谢谢@zhang 的解决方案!就我而言,根据我的项目要求,我有不同的动画(没有背景恒定的不透明度):
在这里查看第一个动画

另外,我有不同的颜色, radius,想要动画自动启动并修改颜色,半径来自 xml。为此,我修改了 LoadingIndicatorView.javaLoadingIndicatorBarView.java 并在 attrs.xmlToolbox.java 中添加了样式code> 未修改(见下文)。

使用示例:

  <utils.ioslikespinner.LoadingIndicatorView
            android:layout_width="100dp"
            android:layout_height="100dp"
            app:color="?colorPrimary"
            app:radius="50dp"/>

如果您有类似的需求,那么这是我的代码:

LoadingIndicatorView.java

package utils.ioslikespinner;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.RotateAnimation;
import android.widget.RelativeLayout;

import com.milence.R;

import java.util.ArrayList;

/**
 * Created by Zhang on 11/02/16 (https://stackoverflow.com/a/35336605/7867180)
 * Modified for design
 *
 * @noinspection ALL
 */
public class LoadingIndicatorView extends RelativeLayout {
    private final Handler handler = new Handler();
    public ArrayList<LoadingIndicatorBarView> arrBars;
    public float radius;
    private Context context;
    private int numberOfBars;

    private int color;
    private boolean isAnimating;
    private int currentFrame;
    private Runnable playFrameRunnable;

    public LoadingIndicatorView(Context context, AttributeSet attrs) {
        super(context, attrs);

        if (attrs != null) {
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.LoadingIndicatorView);

            this.color = typedArray.getColor(R.styleable.LoadingIndicatorView_color, Color.WHITE);
            this.radius = typedArray.getDimension(R.styleable.LoadingIndicatorView_radius, 33);
        }

        this.context = context;
        this.numberOfBars = 12;

        initViews();
        initLayouts();
        addViews();
        spreadBars();

        startAnimating();
    }

    public void initViews() {
        arrBars = new ArrayList<LoadingIndicatorBarView>();

        for (int i = 0; i < numberOfBars; i++) {
            LoadingIndicatorBarView bar = new LoadingIndicatorBarView(context, 100, this.color);

            arrBars.add(bar);
        }
    }

    public void initLayouts() {
        for (int i = 0; i < numberOfBars; i++) {
            LoadingIndicatorBarView bar = arrBars.get(i);

            bar.setId(View.generateViewId());

            RelativeLayout.LayoutParams barLayoutParams = new RelativeLayout.LayoutParams(
                    (int) (radius / 5.0f),
                    (int) (radius / 2.0f)
            );

            barLayoutParams.addRule(ALIGN_PARENT_TOP);
            barLayoutParams.addRule(CENTER_HORIZONTAL);

            bar.setLayoutParams(barLayoutParams);
        }
    }

    public void addViews() {
        for (int i = 0; i < numberOfBars; i++) {
            LoadingIndicatorBarView bar = arrBars.get(i);

            addView(bar);
        }
    }

    public void spreadBars() {
        int degrees = 0;

        for (int i = 0; i < arrBars.size(); i++) {
            LoadingIndicatorBarView bar = arrBars.get(i);

            rotateBar(bar, degrees);

            degrees += 30;
        }
    }

    private void rotateBar(LoadingIndicatorBarView bar, float degrees) {
        RotateAnimation animation = new RotateAnimation(0, degrees, radius / 10.0f, radius);
        animation.setDuration(0);
        animation.setFillAfter(true);

        bar.setAnimation(animation);
        animation.start();
    }

    public void startAnimating() {
        setAlpha(1.0f);

        isAnimating = true;

        playFrameRunnable = new Runnable() {
            @Override
            public void run() {
                playFrame();
            }
        };

        // recursive function until isAnimating is false
        playFrame();
    }

    public void stopAnimating() {
        isAnimating = false;

        setAlpha(0.0f);

        invalidate();

        playFrameRunnable = null;
    }

    private void playFrame() {
        if (isAnimating) {
            resetAllBarAlpha();
            updateFrame();

            handler.postDelayed(playFrameRunnable, 100);
        }
    }

    private void updateFrame() {
        if (isAnimating) {
            showFrame(currentFrame);
            currentFrame += 1;

            if (currentFrame > 11) {
                currentFrame = 0;
            }
        }
    }

    private void resetAllBarAlpha() {
        LoadingIndicatorBarView bar = null;

        float alpha = 1f;


        for (int i = 0; i < arrBars.size(); i++) {
            bar = arrBars.get(i);

            bar.setAlpha(alpha);
        }
    }

    private void showFrame(int frameNumber) {
        int[] indexes = getFrameIndexesForFrameNumber(frameNumber);

        gradientColorBarSets(indexes);
    }

    private int[] getFrameIndexesForFrameNumber(int frameNumber) {
        if (frameNumber == 0) {
            return indexesFromNumbers(0, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1);
        } else if (frameNumber == 1) {
            return indexesFromNumbers(1, 0, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2);
        } else if (frameNumber == 2) {
            return indexesFromNumbers(2, 1, 0, 11, 10, 9, 8, 7, 6, 5, 4, 3);
        } else if (frameNumber == 3) {
            return indexesFromNumbers(3, 2, 1, 0, 11, 10, 9, 8, 7, 6, 5, 4);
        } else if (frameNumber == 4) {
            return indexesFromNumbers(4, 3, 2, 1, 0, 11, 10, 9, 8, 7, 6, 5);
        } else if (frameNumber == 5) {
            return indexesFromNumbers(5, 4, 3, 2, 1, 0, 11, 10, 9, 8, 7, 6);
        } else if (frameNumber == 6) {
            return indexesFromNumbers(6, 5, 4, 3, 2, 1, 0, 11, 10, 9, 8, 7);
        } else if (frameNumber == 7) {
            return indexesFromNumbers(7, 6, 5, 4, 3, 2, 1, 0, 11, 10, 9, 8);
        } else if (frameNumber == 8) {
            return indexesFromNumbers(8, 7, 6, 5, 4, 3, 2, 1, 0, 11, 10, 9);
        } else if (frameNumber == 9) {
            return indexesFromNumbers(9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 11, 10);
        } else if (frameNumber == 10) {
            return indexesFromNumbers(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 11);
        } else {
            return indexesFromNumbers(11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0);
        }
    }

    private int[] indexesFromNumbers(int i1, int i2, int i3, int i4, int i5, int i6, int i7, int i8, int i9, int i10, int i11, int i12) {
        int[] indexes = {i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, i12};
        return indexes;
    }

    private void gradientColorBarSets(int[] indexes) {
        float alpha = 1.0f;

        LoadingIndicatorBarView barView = null;

        for (int i = 0; i < indexes.length; i++) {
            int barIndex = indexes[i];

            barView = arrBars.get(barIndex);


            barView.setAlpha(alpha);
            alpha -= 0.088f;
        }

        invalidate();
    }
}

LoadingIndicatorBarView.java

package utils.ioslikespinner;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.widget.RelativeLayout;


/**
 * Created by Zhang on 11/02/16 (https://stackoverflow.com/a/35336605/7867180)
 * Modified for design
 *
 * @noinspection ALL
 */
@SuppressLint("ALL")
public class LoadingIndicatorBarView extends RelativeLayout {
    private Context context;
    private float cornerRadius;
    private int color;

    public LoadingIndicatorBarView(Context context, float cornerRadius, int color) {
        super(context);

        this.context = context;
        this.cornerRadius = cornerRadius;
        this.color = color;

        initViews();
    }

    public void initViews() {
        setBackground(ToolBox.roundedCornerRectWithColor(color, cornerRadius));

        setAlpha(0.5f);
    }

    public void resetColor() {
        setBackground(ToolBox.roundedCornerRectWithColor(
                Color.argb(255, 255, 255, 255), cornerRadius));

        setAlpha(0.5f);
    }
}

Toolbox.java

package utils.ioslikespinner;

import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Paint;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;

/**
 * Created by Zhang on 11/02/16 (https://stackoverflow.com/a/35336605/7867180)
 */
public class ToolBox {
    private static ToolBox instance;
    public Context context;

    private ToolBox() {

    }

    public synchronized static ToolBox getInstance() {
        if (instance == null) {
            instance = new ToolBox();
        }

        return instance;
    }

    public static ShapeDrawable roundedCornerRectOutlineWithColor(int color, float cornerRadius,
                                                                  float strokeWidth) {
        float[] radii = new float[]{
                cornerRadius, cornerRadius,
                cornerRadius, cornerRadius,
                cornerRadius, cornerRadius,
                cornerRadius, cornerRadius
        };

        RoundRectShape roundedCornerShape = new RoundRectShape(radii, null, null);

        ShapeDrawable shape = new ShapeDrawable();
        shape.getPaint().setColor(color);
        shape.setShape(roundedCornerShape);
        shape.getPaint().setStrokeWidth(strokeWidth);
        shape.getPaint().setStyle(Paint.Style.STROKE);

        return shape;
    }

    public static ShapeDrawable roundedCornerRectWithColor(int color, float cornerRadius) {
        float[] radii = new float[]{
                cornerRadius, cornerRadius,
                cornerRadius, cornerRadius,
                cornerRadius, cornerRadius,
                cornerRadius, cornerRadius
        };

        RoundRectShape roundedCornerShape = new RoundRectShape(radii, null, null);

        ShapeDrawable shape = new ShapeDrawable();
        shape.getPaint().setColor(color);
        shape.setShape(roundedCornerShape);

        return shape;
    }

    public static ShapeDrawable roundedCornerRectWithColor(int color, float topLeftRadius, float
            topRightRadius, float bottomRightRadius, float bottomLeftRadius) {
        float[] radii = new float[]{
                topLeftRadius, topLeftRadius,
                topRightRadius, topRightRadius,
                bottomRightRadius, bottomRightRadius,
                bottomLeftRadius, bottomLeftRadius
        };

        RoundRectShape roundedCornerShape = new RoundRectShape(radii, null, null);

        ShapeDrawable shape = new ShapeDrawable();
        shape.getPaint().setColor(color);
        shape.setShape(roundedCornerShape);

        return shape;
    }

    public static int getScreenWidth() {
        return Resources.getSystem().getDisplayMetrics().widthPixels;
    }

    public static int getScreenHeight() {
        return Resources.getSystem().getDisplayMetrics().heightPixels;
    }

    public static int getScreenOrientation(Context context) {
        return context.getResources().getConfiguration().orientation;
    }

    public static boolean isLandscapeOrientation(Context context) {
        return getScreenOrientation(context) == Configuration.ORIENTATION_LANDSCAPE;
    }

}

attrs .xml

<?xml version="1.0" encoding="utf-8"?>
<!--  ....  -->
<resources>
    <declare-styleable name="LoadingIndicatorView">
        <attr name="color" format="color" />
        <attr name="radius" format="dimension" />
    </declare-styleable>
</resources>

Thank you @zhang for you solution! In my case, according to my project's requirements, I had different animation (without background constant opacity):
see the first animation here

Also, I had different color, radius, wanted animation to start automatically and modify color, radius from the xml. To achieve that, I modified LoadingIndicatorView.java and LoadingIndicatorBarView.java and added style in attrs.xml, Toolbox.java is unmodified (see below).

Example of usage:

  <utils.ioslikespinner.LoadingIndicatorView
            android:layout_width="100dp"
            android:layout_height="100dp"
            app:color="?colorPrimary"
            app:radius="50dp"/>

If you have similar requirements, then this is my code:

LoadingIndicatorView.java

package utils.ioslikespinner;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.RotateAnimation;
import android.widget.RelativeLayout;

import com.milence.R;

import java.util.ArrayList;

/**
 * Created by Zhang on 11/02/16 (https://stackoverflow.com/a/35336605/7867180)
 * Modified for design
 *
 * @noinspection ALL
 */
public class LoadingIndicatorView extends RelativeLayout {
    private final Handler handler = new Handler();
    public ArrayList<LoadingIndicatorBarView> arrBars;
    public float radius;
    private Context context;
    private int numberOfBars;

    private int color;
    private boolean isAnimating;
    private int currentFrame;
    private Runnable playFrameRunnable;

    public LoadingIndicatorView(Context context, AttributeSet attrs) {
        super(context, attrs);

        if (attrs != null) {
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.LoadingIndicatorView);

            this.color = typedArray.getColor(R.styleable.LoadingIndicatorView_color, Color.WHITE);
            this.radius = typedArray.getDimension(R.styleable.LoadingIndicatorView_radius, 33);
        }

        this.context = context;
        this.numberOfBars = 12;

        initViews();
        initLayouts();
        addViews();
        spreadBars();

        startAnimating();
    }

    public void initViews() {
        arrBars = new ArrayList<LoadingIndicatorBarView>();

        for (int i = 0; i < numberOfBars; i++) {
            LoadingIndicatorBarView bar = new LoadingIndicatorBarView(context, 100, this.color);

            arrBars.add(bar);
        }
    }

    public void initLayouts() {
        for (int i = 0; i < numberOfBars; i++) {
            LoadingIndicatorBarView bar = arrBars.get(i);

            bar.setId(View.generateViewId());

            RelativeLayout.LayoutParams barLayoutParams = new RelativeLayout.LayoutParams(
                    (int) (radius / 5.0f),
                    (int) (radius / 2.0f)
            );

            barLayoutParams.addRule(ALIGN_PARENT_TOP);
            barLayoutParams.addRule(CENTER_HORIZONTAL);

            bar.setLayoutParams(barLayoutParams);
        }
    }

    public void addViews() {
        for (int i = 0; i < numberOfBars; i++) {
            LoadingIndicatorBarView bar = arrBars.get(i);

            addView(bar);
        }
    }

    public void spreadBars() {
        int degrees = 0;

        for (int i = 0; i < arrBars.size(); i++) {
            LoadingIndicatorBarView bar = arrBars.get(i);

            rotateBar(bar, degrees);

            degrees += 30;
        }
    }

    private void rotateBar(LoadingIndicatorBarView bar, float degrees) {
        RotateAnimation animation = new RotateAnimation(0, degrees, radius / 10.0f, radius);
        animation.setDuration(0);
        animation.setFillAfter(true);

        bar.setAnimation(animation);
        animation.start();
    }

    public void startAnimating() {
        setAlpha(1.0f);

        isAnimating = true;

        playFrameRunnable = new Runnable() {
            @Override
            public void run() {
                playFrame();
            }
        };

        // recursive function until isAnimating is false
        playFrame();
    }

    public void stopAnimating() {
        isAnimating = false;

        setAlpha(0.0f);

        invalidate();

        playFrameRunnable = null;
    }

    private void playFrame() {
        if (isAnimating) {
            resetAllBarAlpha();
            updateFrame();

            handler.postDelayed(playFrameRunnable, 100);
        }
    }

    private void updateFrame() {
        if (isAnimating) {
            showFrame(currentFrame);
            currentFrame += 1;

            if (currentFrame > 11) {
                currentFrame = 0;
            }
        }
    }

    private void resetAllBarAlpha() {
        LoadingIndicatorBarView bar = null;

        float alpha = 1f;


        for (int i = 0; i < arrBars.size(); i++) {
            bar = arrBars.get(i);

            bar.setAlpha(alpha);
        }
    }

    private void showFrame(int frameNumber) {
        int[] indexes = getFrameIndexesForFrameNumber(frameNumber);

        gradientColorBarSets(indexes);
    }

    private int[] getFrameIndexesForFrameNumber(int frameNumber) {
        if (frameNumber == 0) {
            return indexesFromNumbers(0, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1);
        } else if (frameNumber == 1) {
            return indexesFromNumbers(1, 0, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2);
        } else if (frameNumber == 2) {
            return indexesFromNumbers(2, 1, 0, 11, 10, 9, 8, 7, 6, 5, 4, 3);
        } else if (frameNumber == 3) {
            return indexesFromNumbers(3, 2, 1, 0, 11, 10, 9, 8, 7, 6, 5, 4);
        } else if (frameNumber == 4) {
            return indexesFromNumbers(4, 3, 2, 1, 0, 11, 10, 9, 8, 7, 6, 5);
        } else if (frameNumber == 5) {
            return indexesFromNumbers(5, 4, 3, 2, 1, 0, 11, 10, 9, 8, 7, 6);
        } else if (frameNumber == 6) {
            return indexesFromNumbers(6, 5, 4, 3, 2, 1, 0, 11, 10, 9, 8, 7);
        } else if (frameNumber == 7) {
            return indexesFromNumbers(7, 6, 5, 4, 3, 2, 1, 0, 11, 10, 9, 8);
        } else if (frameNumber == 8) {
            return indexesFromNumbers(8, 7, 6, 5, 4, 3, 2, 1, 0, 11, 10, 9);
        } else if (frameNumber == 9) {
            return indexesFromNumbers(9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 11, 10);
        } else if (frameNumber == 10) {
            return indexesFromNumbers(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 11);
        } else {
            return indexesFromNumbers(11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0);
        }
    }

    private int[] indexesFromNumbers(int i1, int i2, int i3, int i4, int i5, int i6, int i7, int i8, int i9, int i10, int i11, int i12) {
        int[] indexes = {i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, i12};
        return indexes;
    }

    private void gradientColorBarSets(int[] indexes) {
        float alpha = 1.0f;

        LoadingIndicatorBarView barView = null;

        for (int i = 0; i < indexes.length; i++) {
            int barIndex = indexes[i];

            barView = arrBars.get(barIndex);


            barView.setAlpha(alpha);
            alpha -= 0.088f;
        }

        invalidate();
    }
}

LoadingIndicatorBarView.java

package utils.ioslikespinner;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.widget.RelativeLayout;


/**
 * Created by Zhang on 11/02/16 (https://stackoverflow.com/a/35336605/7867180)
 * Modified for design
 *
 * @noinspection ALL
 */
@SuppressLint("ALL")
public class LoadingIndicatorBarView extends RelativeLayout {
    private Context context;
    private float cornerRadius;
    private int color;

    public LoadingIndicatorBarView(Context context, float cornerRadius, int color) {
        super(context);

        this.context = context;
        this.cornerRadius = cornerRadius;
        this.color = color;

        initViews();
    }

    public void initViews() {
        setBackground(ToolBox.roundedCornerRectWithColor(color, cornerRadius));

        setAlpha(0.5f);
    }

    public void resetColor() {
        setBackground(ToolBox.roundedCornerRectWithColor(
                Color.argb(255, 255, 255, 255), cornerRadius));

        setAlpha(0.5f);
    }
}

Toolbox.java

package utils.ioslikespinner;

import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Paint;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;

/**
 * Created by Zhang on 11/02/16 (https://stackoverflow.com/a/35336605/7867180)
 */
public class ToolBox {
    private static ToolBox instance;
    public Context context;

    private ToolBox() {

    }

    public synchronized static ToolBox getInstance() {
        if (instance == null) {
            instance = new ToolBox();
        }

        return instance;
    }

    public static ShapeDrawable roundedCornerRectOutlineWithColor(int color, float cornerRadius,
                                                                  float strokeWidth) {
        float[] radii = new float[]{
                cornerRadius, cornerRadius,
                cornerRadius, cornerRadius,
                cornerRadius, cornerRadius,
                cornerRadius, cornerRadius
        };

        RoundRectShape roundedCornerShape = new RoundRectShape(radii, null, null);

        ShapeDrawable shape = new ShapeDrawable();
        shape.getPaint().setColor(color);
        shape.setShape(roundedCornerShape);
        shape.getPaint().setStrokeWidth(strokeWidth);
        shape.getPaint().setStyle(Paint.Style.STROKE);

        return shape;
    }

    public static ShapeDrawable roundedCornerRectWithColor(int color, float cornerRadius) {
        float[] radii = new float[]{
                cornerRadius, cornerRadius,
                cornerRadius, cornerRadius,
                cornerRadius, cornerRadius,
                cornerRadius, cornerRadius
        };

        RoundRectShape roundedCornerShape = new RoundRectShape(radii, null, null);

        ShapeDrawable shape = new ShapeDrawable();
        shape.getPaint().setColor(color);
        shape.setShape(roundedCornerShape);

        return shape;
    }

    public static ShapeDrawable roundedCornerRectWithColor(int color, float topLeftRadius, float
            topRightRadius, float bottomRightRadius, float bottomLeftRadius) {
        float[] radii = new float[]{
                topLeftRadius, topLeftRadius,
                topRightRadius, topRightRadius,
                bottomRightRadius, bottomRightRadius,
                bottomLeftRadius, bottomLeftRadius
        };

        RoundRectShape roundedCornerShape = new RoundRectShape(radii, null, null);

        ShapeDrawable shape = new ShapeDrawable();
        shape.getPaint().setColor(color);
        shape.setShape(roundedCornerShape);

        return shape;
    }

    public static int getScreenWidth() {
        return Resources.getSystem().getDisplayMetrics().widthPixels;
    }

    public static int getScreenHeight() {
        return Resources.getSystem().getDisplayMetrics().heightPixels;
    }

    public static int getScreenOrientation(Context context) {
        return context.getResources().getConfiguration().orientation;
    }

    public static boolean isLandscapeOrientation(Context context) {
        return getScreenOrientation(context) == Configuration.ORIENTATION_LANDSCAPE;
    }

}

attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<!--  ....  -->
<resources>
    <declare-styleable name="LoadingIndicatorView">
        <attr name="color" format="color" />
        <attr name="radius" format="dimension" />
    </declare-styleable>
</resources>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文