【问题标题】:Run a method with a Timer使用 Timer 运行方法
【发布时间】:2015-07-07 13:15:36
【问题描述】:

我有一个 void 方法,其中包含一些 findViewById,我想每秒运行一次。我怎样才能做到这一点? 我想出的是这样的:

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  timer.schedule(new TimerTask() {
    public void run() {
       Method();
    }
  }, 1000, 1000);
}

public void Method() {
  findViewById(R.id.textView1).setVisibility(View.INVISIBLE);
  ((TextView) findViewById(R.id.textView1)).setText("A second has passed!");
}

【问题讨论】:

  • 你有没有在某个地方创建过这个 Timer timer = new Timer(); ?在课堂上
  • 是的,定时器已经创建好了。
  • 发布整个代码而不是部分代码总是很好的,因为没有人会通过查看知道findViewById() 和其他内容是什么
  • 接受的答案是指“以 Android 方式进行操作”。一方面,我不知道这是一个 android 问题。您可能应该提到这一点和/或相应地标记问题......
  • @dcsohl 当你在OP问题中看到onCreate方法时,你一定注意到它是Android问题。

标签: java android methods timer timertask


【解决方案1】:

将您的业务逻辑插入到 run 方法中。这将被调用。

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  timer.schedule(new TimerTask() {
    public void run() {
      findViewById(R.id.textView1).setVisibility(View.INVISIBLE);
  ((TextView) findViewById(R.id.textView1)).setText("A second has passed!");
    }
  }, 1000, 1000);
}

【讨论】:

  • 不起作用。应用程序一启动就崩溃。
猜你喜欢
  • 2019-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多