我正在使用倒数计时器倒计时这是我的代码:
public class countdownnow extends Activity{
TextView tv;
private CDwnTimer countDownTimer;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.countdown_disp);
tv = (TextView)findViewById(R.id.textView1);
countDownTimer = new MalibuCountDownTimer(30000, 1050);
countDownTimer.start();
}
// CountDownTimer class
public class CDwnTimer extends CountDownTimer {
public CDwnTimer(long startTime, long interval) {
super(startTime, interval);
}
@Override
public void onFinish() {
tv.setText("00");
}
@Override
public void onTick(long millisUntilFinished) {
int convert = (int) millisUntilFinished/1000;
String testString = String.format("%02d",convert);
CharSequence cs = new String(testString);
tv.setText(cs);
}
}
}
最初这种方法很好但是当我离开这个活动然后去另一个活动然后回来时,textview不再倒计时了? TextView tv继续在该行中运行,但它不会更新。活动是否已释放并初始化Textview的相同ID?任何提示都会很棒。谢谢。
答案 0 :(得分:0)
你是怎么离开活动的?
我模拟了你的程序,当我将MainActivity留给OtherActivity并返回时,textView继续倒计时。代码如下:
public class MainActivity extends Activity {
private CDwnTimer countDownTimer;
private Button btn;
private TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.tv);
btn = (Button) findViewById(R.id.btnEnter);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// call sendMessage method
Intent startActivityIntent =new Intent(MainActivity.this, OtherActivity.class);
MainActivity.this.startActivity(startActivityIntent);
}
});
countDownTimer = new CDwnTimer(30000, 1050);
countDownTimer.start();
}
// CountDownTimer class
public class CDwnTimer extends CountDownTimer {
public CDwnTimer(long startTime, long interval) {
super(startTime, interval);
}
@Override
public void onFinish() {
tv.setText("00");
}
@Override
public void onTick(long millisUntilFinished) {
int convert = (int) millisUntilFinished/1000;
String testString = String.format("%02d",convert);
CharSequence cs = new String(testString);
tv.setText(cs);
}
}
}
MainActivity布局的main.xml文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:layout_weight="6"/>
<Button
android:id="@+id/btnEnter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="282dp"
android:layout_marginLeft="21dp"
android:text="Button"
android:layout_weight="2"/>
</LinearLayout>