安卓活动指示器?

57

如何在安卓中显示活动指示器?是否有任何给定方法的安卓库?如果没有,请告诉我在安卓中显示活动指示器所使用的技巧。


你的意思是类似于独立无限进度指示器,就像在 ProgressDialog(http://developer.android.com/guide/topics/ui/dialogs.html#ProgressDialog)中使用的那种吗? - Olegas
“Activity indicator”这个词在Android中与“Activity”类和概念非常相似,容易混淆...我一开始并没有意识到它可能是指进度对话框/进度条 :-) 但是在Android中还有一些我不知道正确名称的东西,因此无法很好地进行搜索。 - Heiko Rupp
5个回答

100
在安卓系统中,iOS活动指示器最直接的对应物是ProgressBar,但需将其设置为不定进度。因此,您可以将该视图放入布局中,它会提供旋转动画。
<ProgressBar
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:id="@+id/ctrlActivityIndicator"
    android:indeterminateOnly="true"
    android:keepScreenOn="true"
     />

你可以使用这个来向用户指示一些后台活动。

2
如何更改圆形进度条的颜色? - Teja Nandamuri
要更改颜色,最简单的方法可能是使用Olegas的答案,然后您可以指定自己喜欢的任何颜色的可绘制对象。否则,您可能需要复制SDK源代码中的ProgressBar并为其提供自己的可绘制对象。 - Martin Belcher - AtWrk

57

做一些像这样的事情

ProgressDialog mDialog = new ProgressDialog(getApplicationContext());
            mDialog.setMessage("Please wait...");
            mDialog.setCancelable(false);
            mDialog.show();

2
如果你遇到了 WindowManager$BadTokenException 异常,请参考 https://dev59.com/GHI_5IYBdhLWcg3wBuRs - Dan F
3
如果您想让对话框看起来像有旋转图标而不是进度条,可以使用setProgressStyle(STYLE_SPINNER)。相当于在警报中使用iOS ActivityIndicator。 - Martin Belcher - AtWrk
6
那段代码给了我很长的错误信息(并导致了崩溃),其中一部分是“Caused by: android.view.WindowManager $ BadTokenException:无法添加窗口--令牌为空不是应用程序”。因此,我使用了以下代码替换答案中的代码:“ProgressDialog mDialog = ProgressDialog.show(this,“对话框标题”,“对话框消息”,true);” - Sufian
3
如果在一个活动中出现了bad token异常,你可以通过将ProgressDialog mDialog = new ProgressDialog(getApplicationContext());替换为ProgressDialog mDialog = new ProgressDialog(this);来解决。 - Chris
2
ProgressDialog现在已被标记为过时,我不建议使用。 - Xander
显示剩余5条评论

21

在不使用模态 ProgressDialog 的情况下,有两种其他方法可以显示活动指示器。

您可以在布局中使用 ImageView 并对其应用动画。请参阅开发者网站的旋转动画

public void startAnimation() {
  // Create an animation
  RotateAnimation rotation = new RotateAnimation(
      0f,
      360f,
      Animation.RELATIVE_TO_SELF,
      0.5f,
      Animation.RELATIVE_TO_SELF,
      0.5f);
  rotation.setDuration(1200);
  rotation.setInterpolator(new LinearInterpolator());
  rotation.setRepeatMode(Animation.RESTART);
  rotation.setRepeatCount(Animation.INFINITE);

  // and apply it to your imageview
  findViewById(R.id.myActivityIndicator).startAnimation(rotation);
}

或者你可以使用xml-drawable来描述背景图像,这样就会有一些旋转动画:

首先描述一个drawable(比如/res/drawable/my-indicator.xml)

<animated-rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/spinner_black_76"
    android:pivotX="50%"
    android:pivotY="50%"
    android:framesCount="12"
    android:frameDuration="100" />

然后将其设置为某个视图的背景


1
如何停止动画? - Henley
停止动画,调用 yourImageView.clearAnimation() 并设置 yourImageView.isVisible = false。要重新启动它,您必须从头开始,如 yourImageView.startAnimation(startAnimation()) 并设置 yourImageView.isVisible = true - Lance Samaria

5
public class Mp3cutterActivity extends Activity {

    MP3Class mp3obj = null;
    TextView tv;
    MP3Class mp3classobj = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Context thiscontext = this.getApplicationContext();
        mp3classobj = new MP3Class(thiscontext);
        setContentView(R.layout.main);

        Button btn = (Button)findViewById(R.id.startbutton);
        tv = (TextView)findViewById(R.id.textview1);
        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //show a wait indicator as well as the function that calls walkSdcard

                try {
                    new SearchSdCard(Mp3cutterActivity.this).execute();
                    // copyProtector.doCopyProtection();
                } catch (Exception e) {
                    System.out.println("in search SD card  " + e.getMessage());
                }
            }

            private void domp3stuff() {
                // TODO Auto-generated method stub
            }
        });
    }
}

class SearchSdCard extends AsyncTask<String, Void, Boolean> {

    Context context;    

    public ProgressDialog dialog;

    public SearchSdCard(Activity activity) {
        this.context = activity;
    }

    protected void onPreExecute() {
        dialog = new ProgressDialog(context);
        dialog.setMessage("wait for a moment...");
        dialog.show();
    }

    @Override
    protected Boolean doInBackground(String... params) {
        // TODO Auto-generated method stub
        boolean retval = true;
        mp3classobj.searchSdCard();
        return retval;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        // TODO Auto-generated method stub
        if (dialog.isShowing()) {
            dialog.dismiss();
            tv.setText("mp3 cutter is an app which cuts down a chunk of memory \nfrom your sdcard by \ndeleting the .mp3 files and more \nyou were made a BAKRA :-)");
            if(!result){    
                tv.setText("error occured !!");
            }
        }
    }
    //refer below comment for the MP3class.java file details
}

1
公共类 MP3Class { private Context mcontext; public MP3Class(Context context){ mcontext = context; } public void searchSdCard() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { // 我的功能在这里,您可以添加您自己的 } } - sudatt

2

活动指示器其实就是进度对话框。你可以通过编程创建它。有许多教程可用,搜索如何创建进度对话框/进度条。

ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setMax(100);
                progressDialog.setMessage("Its loading....");
                progressDialog.setTitle("ProgressDialog bar example");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
or
progressDialog.setProgressStyle(ProgressDialog.STYLE_CIRCULAR);

您可以通过使用 XML 创建它,一旦任务完成,请将可见性设置为 visible,然后将其设置为 gone

<ProgressBar
                android:id="@+id/loading_spinner"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="100dp"
                android:indeterminateTintMode="src_atop"
                android:indeterminateTint="@color/grey"
                android:layout_gravity="center" />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接