为什么我只看到“第一次”吐司而不是其他(应该)从我的帖子中创建?
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();
}
}
}
}
答案 0 :(得分:1)
Looper.prepare
。你得到了例外,因为你做错了什么:AsyncTask
交换Thread
并使用onProgressUpdate
方法创建吐司,因为这会自动在UI线程上运行。否则你需要使用一个处理程序。getBaseContext
而不是当前活动的上下文传递给构造函数