0

下面是我的代码不起作用,我不明白为什么它说“只有创建视图层次结构的原始线程才能触及它的视图。” 当我想在 LoadValues() 方法中为我的列表视图设置适配器时.. “listView.setAdapter(adapter)”

public class ProgressDialogActivity extends Activity {

    private ProgressDialog progressDialog;  
    private ListView listView;
    private ArrayList<String> lstValores;
    private Handler progressBarHandler = new Handler();

    private int mProgressStatus, mProgressTotal;    

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

        lstValores = new ArrayList<String>();
        listView = (ListView) findViewById(R.id.listView1);

        this.LoadValues();

    }//onCreate   


    public void LoadValues(){

        progressDialog = new ProgressDialog(ProgressDialogActivity.this);
        progressDialog.setTitle("Aguarde..");
        progressDialog.setMessage("Cargando lista..");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setProgress(0);
        progressDialog.show();

        new Thread(new Runnable() {         
            public void run() {         

                mProgressTotal = (int) 1000;

                try {
                    for (int i = 0; i < mProgressTotal; i++) {

                        lstValores.add("valor " + i);

                        mProgressStatus = (int) ((i * 100) / mProgressTotal);

                        progressBarHandler.post(new Runnable() {                        
                            public void run() {
                                progressDialog.setProgress(mProgressStatus);
                                }
                            });                 
                        }// end for      

                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(ProgressDialogActivity.this, 
                                                                                R.layout.textviewlist_layout, 
                                                                                lstValores);
                        listView.setAdapter(adapter);                       
                        progressDialog.dismiss();

                } catch (Exception e) {
                    e.printStackTrace();                
                }

            }// end run
        }).start();// end Thread        
    }// end LoadValues


} // Activity
4

1 回答 1

0

In android, Only the UI Thread can touch the View.

So

progressBarHandler.post(new Runnable() {
     public void run(){
          listView.setAdapter(adapter);                       
     }                        
}                    
于 2012-05-08T03:39:04.293 回答