How to force the change the image of a view immediately after calling setImageResource?

*爱你&永不变心* 提交于 2019-12-13 03:56:13

问题


I'm trying to change the image of a ImageView immediately after I click it.

I tried using .setImageDrawable and calling .invalidate() on that view, without any success.

I'm probably not doing it right, but I'm trying to click the image, put the Thread to sleep for 2 seconds then display another image to the user.

The code is quite simple, and it's something like this:

myImage.setImageResource(R.id.myPicture);
... computations
... put the thread to sleep for 2 seconds
myImage.setImageResource(R.id.newPicture);

and the user can't see "myPicture" for those 2 seconds of sleep, and then it changes to "newPicture"


回答1:


You can use sendMessageDelayed() method of handler to perform any task at a delay of some specific amount of time. and write the logic to setImageDrawable inside that handler

See the sample code

@Override
    public void onClick(View v) {

        Message msg = new Message();
        photoGridHandler.sendMessageDelayed(msg, 2000);// delay of 2000 milisecond = 2 second

    }


    private Handler photoGridHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            photoGrid.setImageDrawable(myImage);

        };
    };



回答2:


Try using image.setBackgroundResource(R.drawable.newimage);. Place both the images in your drawable folder




回答3:


I had similar issues when mixing the UI thread and computations thread. I would recommend trying an AsyncTask and pass it imageView. Do your computations in the doInBackground of the asynctask and then in the onPostExecute change the image.

http://developer.android.com/reference/android/os/AsyncTask.html



来源:https://stackoverflow.com/questions/8653053/how-to-force-the-change-the-image-of-a-view-immediately-after-calling-setimagere

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