【发布时间】:2014-07-23 16:31:44
【问题描述】:
我有图像数组,我想每 5 秒随机更改一次背景图像。 我写了一些代码,但我有 android.view.ViewRootImpl$CalledFromWrongThreadException: 只有创建视图层次结构的原始线程才能接触其视图,例外。这个问题的解决方法是什么。
public class StradaContact extends Fragment {
private int[] image_rundow = {
R.drawable.slideone, R.drawable.slidetwo, R.drawable.slidetree
};
private ImageView mapimg;
Reminder claass;
public StradaContact() {
}
public static StradaContact newInstance() {
return new StradaContact();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.strada_contact, container,
false);
claass = new Reminder(5);
return rootView;
}
public class Reminder {
Timer timer;
public Reminder(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds * 1000);
}
class RemindTask extends TimerTask {
public void run() {
while (true) {
Random rand = new Random();
int index = rand.nextInt(image_rundow.length);
mapimg.setBackgroundResource(image_rundow[index]);
timer.cancel();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Terminate the timer thread
}
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
【问题讨论】:
-
正如异常所说,只有创建视图的线程才能更改其属性。查看 AysncTask 或 View.PostDelayed
标签: java android android-imageview