【问题标题】:Java for Android timerJava for Android 计时器
【发布时间】:2013-10-27 16:38:29
【问题描述】:

你能告诉我这一行的问题出在哪里吗:timerText.setText(seconds);

public class ShowTimer extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.timer_test_xml);

        Timer myTimer = new Timer();
        myTimer.schedule(new TimerTask() {
            int seconds;
            TextView timerText = (TextView) findViewById(R.id.TimerTestId);
            @Override
            public void run() {
                seconds++;
                timerText.setText(seconds);
            }
        }, 0, 1000);

    }}

【问题讨论】:

  • android 上的setText(int) 函数没有文档,所以我真的不知道它是做什么的。你确定它是你要调用的函数吗?
  • 如果我们把一个字符串作为方法的参数还是不行:)
  • 您希望发生什么以及实际发生了什么?

标签: java android timer clock


【解决方案1】:

我认为您想要做的是在文本视图中显示seconds。但是,TextView.setText(int) 函数并没有这样做(我实际上不确定它的作用)。您要做的是timerText.setText(""+seconds); 将参数转换为字符串并将函数调用更改为不同的重载函数。

【讨论】:

    【解决方案2】:

    seconds 是一个 int,而我认为您希望作为字符序列传递,或者通过资源 ID as per the documentation 引用一个字符序列。

    【讨论】:

      【解决方案3】:

      虽然这不能回答 OP 的原始问题,但在 this thread 中描述了其他方法(并且 - 如果您同意 Android 文档的建议 - 更好)。

      【讨论】:

        【解决方案4】:

        与 Richard 的建议一样,您的另一个问题是在非 UI 线程上更新 TextView,因此请考虑使用 Handler

        例子

        public class ShowTimer extends Activity {
        
            private Handler mHandler;
            private TextView timerText = null;
            private int seconds;
        
            private Runnable timerRunnable = new Runnable() {
                @Override
                public void run() {
                    timerText.setText(String.valueOf(seconds++));
                    mHandler.postDelayed(timerRunnable, 1000);
                }
            };
        
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.timer_test_xml);
        
                mHandler = new Handler();
        
                timerText = (TextView) findViewById(R.id.TimerTestId);
                timerRunnable.run();
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-10-17
          • 1970-01-01
          • 2015-04-04
          • 1970-01-01
          相关资源
          最近更新 更多