简体   繁体   English

Java for Android计时器

[英]Java for Android timer

Can you tell me where is the problem on this line: timerText.setText(seconds); 你能告诉我这行的问题在哪里吗: 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);

    }}

I think what you want to do is display seconds in the text view. 我认为您要在文本视图中显示seconds However, the TextView.setText(int) function does not do this (Im not actually sure what it does). 但是, TextView.setText(int)函数不会执行此操作(实际上我不确定该执行的操作)。 What you want to do is timerText.setText(""+seconds); 您想要做的是timerText.setText(""+seconds); to convert the parameter into a string and change the function call to a different overloaded function. 将参数转换为字符串并将函数调用更改为其他重载函数。

seconds是一个int ,而我认为您希望按照文档中的字符序列或通过资源ID引用一个字符进行传递。

尽管这不能回答OP的原始问题,但此线程中介绍了替代方法(并且-如果您同意Android文档的建议-更好)。

As with Richard's suggestion, your other problem is updating the TextView on the non-UI thread, so consider using a Handler . 与Richard的建议一样,您的另一个问题是在非UI线程上更新TextView,因此请考虑使用Handler

Example

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM