views:

76

answers:

2

Hi all, 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;
}
A: 

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.

Mathias Lin
+1  A: 

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

Kevin Gaudin
hi kevin, good to see you here on SO :) yes, I agree, your approach is more elegant; I was just looking at stefano's existing code. wasn't aware of postDelayed method actually. good to know.
Mathias Lin