why ImageView can't update before SystemClock.sleep()

≯℡__Kan透↙ 提交于 2019-12-19 11:06:07

问题


I want to show other image in ImageView within 3 second, after that rollover old image. The code:

    OnClickListener oc = new OnClickListener() {
@Override
public void onClick(View v) {
         ImageView iv = (ImageView)v;
         iv.setImageResource(img2_id);
         SystemClock.sleep(3000);
         iv.setImageResource(img1_id);
    }
    }

    myImageView.setOnClickListener(oc);

But it doesn't work? So, am I doing something wrong?


回答1:


You are blocking the UI thread. Thus during the sleep command, the screen won't refresh. What you need is to schedule a non-blocking delayed call to a function which changes image resource. Here is a modified code that would do such a thing:

Handler mHandler = new Handler(); /*handler declared in your Activity thread, I assume*/

OnClickListener oc = new OnClickListener() {
    @Override
    public void onClick(View v) {
        ImageView iv = (ImageView)v;
        iv.setImageResource(img2_id);

        mHandler.postDelayed(new Runnable(){
            public void Run(){
                iv.setImageResource(img1_id);
            }
        },3000);

    }
}
myImageView.setOnClickListener(oc);


来源:https://stackoverflow.com/questions/10368919/why-imageview-cant-update-before-systemclock-sleep

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!