How come this timer code is saying setText cannot be resolved or is not a variable?
package com.android.countdown;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.widget.TextView;
public class CountDownTest extends Activity {
TextView tv; //textview to display the countdown
/** Called when the activity is first created. */
@Over开发者_如何转开发ride
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
this.setContentView(tv);
//5000 is the starting number (in milliseconds)
//1000 is the number to count down each time (in milliseconds)
MyCount counter = new MyCount(5000,1000);
counter.start();
}
//countdowntimer is an abstract class, so extend it and fill in methods
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
tv.setText(”done!”);
}
@Override
public void onTick(long millisUntilFinished) {
tv.setText(”Left: ” + millisUntilFinished/1000);
}
You're redeclaring 'tv' in your oncreate, so you've not set it as a new textView. Change this line:
TextView tv = new TextView(this);
into
tv = new TextView(this);
edit: Another problem: you hav a separate counter class. That class cannot access the properties of your countDownTest activity. So the "tv" variable is empty there. You cannot just have a random subclass use the vars of your superclass. I think you should go back to the design of your classes, and figure out what goes where?
In the meantime, if you're just testing, you could do something like this:
give your textview an id (with setId()
i think).
Get your textview using findViewById()
in your mycount class.
Use that to change the text.
or
Add a memeber to your MyCount that has a parameter "textview", and call that with your origional tv var.
nanne is right just delete type before this line tv = new TextView(this);
However that is the only change yo need to make because your class is an inner class of this activity and you have defined tv to be a varibale for all activity which includes all methods and inner classes in it.
With that change this code works, I've just tested it.
But if your MyCount file is in a separate .java file, then you need to pass this view like this:
MyCount counter = new MyCount(5000,1000, tv);
end MyCount class would look like this:
public class MyCount extends CountDownTimer{
TextView tv;
public MyCount(long millisInFuture, long countDownInterval, TextView tvx) {
super(millisInFuture, countDownInterval);
tv = tvx;
}
@Override
public void onFinish() {
tv.setText("done!");
}
@Override
public void onTick(long millisUntilFinished) {
tv.setText("Left: " + millisUntilFinished/1000);
}}
精彩评论