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;
}
I think you would better use View.postDelayed(Runnable, long) in the onClickListener of your ImageViews to do this.
Approach 1)
Let the thread sleep in
doInBackground
, but change the resource inmethod of the AsyncTask. This method has access to the UI thread.
Approach 2)
Another way might be to use
(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.