几秒钟后更改 ImageView [英] Change ImageView after few seconds

查看:32
本文介绍了几秒钟后更改 ImageView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个简单的活动,让用户插入密码.我有一个网格视图,其中包含 9 个要使用的图像和 4 个将成为选定图像的图像视图(单击网格视图上的项目,相应的图像将被选定的图像填充).

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).

现在的问题:我希望 4 个图像视图的行为类似于密码字段:1 秒钟出现所选项目,然后出现另一个图像...我尝试使用 asyncthread,但出现错误:只有创建视图层次结构的原始线程才能触及其视图这是我的代码:

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;
}

推荐答案

方法一)

让线程在doInBackground中休眠,但是在

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

@Override
protected void onPostExecute(Void aVoid) {}

AsyncTask 的方法.此方法可以访问 UI 线程.

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

方法 2)

另一种方法可能是使用

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

(从 doInBackground 调用)其中 passfield 不是局部变量而是类变量.

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

但是方法1是首选方法,我建议你先试试.

这篇关于几秒钟后更改 ImageView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆