简体   繁体   中英

Java for Android timer

Can you tell me where is the problem on this line: 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. However, the TextView.setText(int) function does not do this (Im not actually sure what it does). What you want to do is 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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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