1

为什么我只看到“第一个”吐司而不是其他(应该)从我的线程创建的吐司?

public class BannerExample extends Activity {

    @Override
    public void onCreate(final Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        Toast toast = Toast.makeText(this, "first toast", Toast.LENGTH_SHORT);
        toast.show();

        new MyThread(this).start();

    }

    class MyThread extends Thread {

        private Context context;

        public MyThread(Context context) {
            this.context = context;
        }

        public void run() {

            Looper.prepare(); // An exception told me to add this - i have no clue why

            for (int i = 0; i < 3; i++) {

                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                Toast toast = Toast.makeText(context, i + "whoho", Toast.LENGTH_SHORT);
                toast.show();
            }

        }

    }

}
4

1 回答 1

1
  1. 你不应该打电话Looper.prepare。你得到异常是因为你做错了什么:
  2. Toast 是 UI 工具包的一部分,因此必须从 UI 线程访问 - 这就是您遇到异常的原因
  3. 我建议您交换ThreadAsyncTask使用该onProgressUpdate方法来创建您的 toast,因为它会自动在 UI 线程上运行。否则,您将需要使用处理程序。
  4. 将上下文getBaseContext而不是当前活动的上下文传递给您的构造函数
于 2011-03-27T19:17:55.163 回答