编辑文本框的计时器:只有创建视图层次结构的原始线程才能接触其视图



如果输入了错误的密码,我正在尝试使编辑文本框振动并立即更改颜色

final Drawable oldBackground = findViewById(R.id.email).getBackground();
TimerTask timerTask = new TimerTask() {
    @Override
    public void run() {
        MainActivty.this.findViewById(R.id.password).setBackground(oldBackground);
        MainActivty.this.findViewById(R.id.email).setBackground(oldBackground);
    }
};

Toast.makeText(MainActivty.this , valArray.get(0).toString(), Toast.LENGTH_SHORT).show();
findViewById(R.id.password).setBackgroundColor(Color.RED);
findViewById(R.id.email).setBackgroundColor(Color.RED);
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(500);Timer timer = new Timer();
timer.schedule(timerTask, 1000);

Timer任务在不同的线程上运行。Ui线程上应该更新Ui。

使用runOnUiThread或使用Handler

          runOnUiThread(new Runnable(){
              @Override
              public void run(){
               // update ui here  
              }
           });

处理器

Handler m_handler;
Runnable m_handlerTask ;  
m_handler = new Handler();   
m_handlerTask = new Runnable()
{
  @Override 
  public void run() { 
    // do something  
    m_handler.postDelayed(m_handlerTask, 1000);    
  }
  };
 m_handlerTask.run();

您也可以使用倒计时

以分钟和秒为单位的倒计时

您必须通过runOnUiThread使用Timer类似方法:

final TextView lblSSID = (TextView)findViewById(R.id.lblWifiSSID);
    new Timer().scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new TimerTask() {
                @Override
                public void run() {
                    lblSSID.setText(networkConnection.getWifiName());
                }
            });
        }
    }, 0, 5000);

最新更新