0

この行の問題点を教えてください: 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);

    }}
4

4 に答える 4

0

リチャードの提案と同様に、他の問題は非 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();
    }
}
于 2013-10-27T17:11:14.533 に答える