Change ImageView after few seconds

2020-05-01 16:26发布

I'm trying to implement a simple activity that will let user to insert a password. I've a gridview with the 9 images to use and 4 imageviews that will be the selected images (on clicking on item on gridview, the corresponding image will be filled with the selected one).

Now the problem: I want that the 4 imageviews acts similar to password fields: for 1 seconds appears the selected item and then another image... I tried using asyncthread but I got and error: Only the original thread that created a view hierarchy can touch its views Here my code:

@Override
protected String doInBackground(ImageView... imageViews) {
    ImageView passField1 = imageViews[0];
    ImageView passField2 = imageViews[1];
    ImageView passField3 = imageViews[2];
    ImageView passField4 = imageViews[3];
    try {
        switch (currentField) {
        case 1:
            passField1.setImageResource(//selected recource on grid view);
            Thread.sleep(1000);
            passField1.setImageResource(R.drawable.e00); //this is a blank image
            break;
        case 2:
            passField2.setImageResource(//selected recource on grid view);
            Thread.sleep(1000);
            passField1.setImageResource(R.drawable.e00);
            break;
        case 3:
            passField3.setImageResource(//selected recource on grid view);
            Thread.sleep(1000);
            passField1.setImageResource(R.drawable.e00);
            break;
        case 4:
            passField4.setImageResource(//selected recource on grid view);
            Thread.sleep(1000);
            passField1.setImageResource(R.drawable.e00);
            break;
        }
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}

2条回答
姐就是有狂的资本
2楼-- · 2020-05-01 17:06

I think you would better use View.postDelayed(Runnable, long) in the onClickListener of your ImageViews to do this.

查看更多
爷的心禁止访问
3楼-- · 2020-05-01 17:25

Approach 1)

Let the thread sleep in doInBackground, but change the resource in

@Override
protected void onPostExecute(Void aVoid) {}

method of the AsyncTask. This method has access to the UI thread.

Approach 2)

Another way might be to use

YourActivity.this.runOnUiThread(new Runnable() {
  public void run() {
    YourActivity.this.passField1.setImageResource(R.drawable.e00)
  }
});

(called from doInBackground) where passfield is not a local variable but class variable.

But approach 1 is the preferred way, I suggest you try that way first.

查看更多
登录 后发表回答