无法更新内部进度条和警报对话框构建器

时间:2015-02-17 23:58:12

标签: android android-activity android-fragments progress-bar progressdialog

我正在尝试在警告对话框构建器中创建一个进度条,并尝试在使用线程和处理程序点击按钮时更新进度.....但每次我点击开始按钮它都会崩溃...

package com.example.progressbar_thread;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;

public class MainActivity extends Activity implements OnClickListener {

Button Start;
int i = 0;
Handler myHandler = new Handler();
ProgressBar myProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Start = (Button) findViewById(R.id.StartButton);
    Start.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    // Alert dialog builder section 
    AlertDialog.Builder myDialogBuilder = new AlertDialog.Builder(this);
    myDialogBuilder.setTitle("Progress...");
    View ProgressView = getLayoutInflater().inflate(R.layout.progressbar,
            null);
    myProgressBar=(ProgressBar)findViewById(R.id.ProgressBar);   

    myDialogBuilder.setView(ProgressView);
    myDialogBuilder.create().show();

    new Thread(new Runnable() {

        @Override
        public void run() {

            // TODO Auto-generated method stub
            while (i < myProgressBar.getMax()) {

                myHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        myProgressBar.setProgress(i);   //Updading progress 

                    }

                });

                i++;

            }

        }
    }).start();

    }

    }enter code here

1 个答案:

答案 0 :(得分:0)

你必须稍微改变你的代码......

您必须更改以下行

 View ProgressView = getLayoutInflater().inflate(R.layout.progressbar,
        null);
myProgressBar=(ProgressBar)findViewById(R.id.ProgressBar);   

myDialogBuilder.setView(ProgressView);
myDialogBuilder.create().show();

要----

 View ProgressView = getLayoutInflater().inflate(R.layout.progressbar,
        null);
myProgressBar=(ProgressBar)ProgressView.findViewById(R.id.ProgressBar);   

myDialogBuilder.setView(myProgressBar);
myDialogBuilder.create().show();

我希望它会对你有帮助.....