【问题标题】:call setListAdapter() from inside a thread从线程内部调用 setListAdapter()
【发布时间】:2010-06-15 18:31:30
【问题描述】:

我的 ListActivity 有问题,我使用线程显示 ProgressDialog,其中获取所有已安装应用程序的列表。我把它变成了一个列表适配器,然后我想设置活动的列表适配器,但我不能从线程中做到这一点。

我收到以下错误:ERROR/AndroidRuntime(14429): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("Loading...");
progressDialog.show();
new Thread() {
        public void run() {
              showList(); // the method where i get all the apps and have the setListAdapter(); method
              progressDialog.dismiss();
        }
}.start();

如何获取它,以便可以在我的线程中使用 setListAdapter

【问题讨论】:

    标签: android listactivity listadapter


    【解决方案1】:

    我解决了这个问题,通过使用处理程序,我设法将 setListAdapter 从线程中取出,并仍在等待线程执行该方法。

    final Handler h = new Handler(){
        public void handleMessage(Message msg) {
            setListAdapter(appsAdapter);
        }           
    };
    
    new Thread() {
        public void run() {
            showList();
            progressDialog.dismiss();
            h.sendEmptyMessage(0);
        }
    }.start();
    

    【讨论】:

      【解决方案2】:

      最简单的方法是使用 Activity 的runOnUiThread 方法:

      runOnUiThread(new Runnable() {
          public void run() {
              showList();
              progressDialog.dismiss();
          }
      });
      

      编辑:将线程更改为可运行

      【讨论】:

      • 两者都不起作用,因为现在我的 ProgressDialog 不再出现,这是将方法放在单独的线程中的主要原因。
      • progressDialog 是一个字段,直接在上面填写(问题已编辑)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-18
      • 1970-01-01
      • 2020-03-11
      • 2015-03-06
      • 2015-11-24
      相关资源
      最近更新 更多