为android创建进度条

时间:2015-01-09 18:33:06

标签: java android multithreading user-interface runnable

您好我是新手一般的线程,我正在尝试设置一个进度条,使用sleep方法每半秒增加一次到100。我一直在使用我在网上找到的很多语法时遇到问题,当我启动这个程序时,它不显示进度条,而是显示一个旋转加载图标。这就是我所拥有的:

public class main extends ActionBarActivity {
Handler mHandler;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final Button startButton = (Button) findViewById(R.id.startbutton);

    startButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showDialog(1);
            startPb();
        }
    });
}
private void startPb(){

    final ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar);
    pb.setIndeterminate(false);
    pb.setProgress(0);
    new Thread(new Runnable(){

        public void run(){
            for (int i = 0; i <= 100; i++)
                try {
                    Thread.sleep(500);
                    pb.setProgress(i);
                    System.out.println(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            pb.post(new Runnable() {
                public void run() {
                    pb.incrementProgressBy(1);
                }
            });

        }
    }).start();
}

我感觉我没有在上面的代码中正确实现进度条。 布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".Counter"
android:id="@+id/counter"
tools:ignore="InvalidId">

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="startButton"
    android:id="@+id/startbutton"
    android:layout_centerHorizontal="true" />

<ProgressBar
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/progressBar"
    android:layout_below="@+id/startbutton"
    android:layout_centerHorizontal="true" />

</RelativeLayout>

1 个答案:

答案 0 :(得分:1)

旋转进度条是一个不确定的进度条。要使用实际进度条,您需要调用:

pb.setIndeterminate(false);

进度条样式也是一个问题。这是一个很好的参考,解释进度条样式类型。 What's the meaning of android:progressBarStyle attribute in ProgressBar?

相关问题