我有一个TextView
,我想用我的字符串数组中的每个字符串每5秒更新一次TextView
。
这是我试过的代码。它始终只显示String数组中的最后一个String。
TextView display;
EditText caption;
Thread thread;
String blinks;
String[] wc;
private CountDownTimer timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = (TextView) findViewById(R.id.display);
caption = (EditText) findViewById(R.id.caption);
timer = new CountDownTimer(5000, 20) {
@Override
public void onTick(long millisUntilFinished) {
String[] wc = {"The","Qucik", "Brown","fox","Jumped"};
for (int j = 0; j < wc.length; j++) {
blinks = wc[j];
final String[] titles = {"" + blinks + ""};
for (int i = 0; i < titles.length; i++) {
display.setText(titles[i]);
}
}
}
@Override
public void onFinish() {
try{
yourMethod();
}catch(Exception e){
}
}
}.start();
}
答案 0 :(得分:2)
final String[] wc = {"The", "Qucik", "Brown", "fox", "Jumped"};
final android.os.Handler handler = new android.os.Handler();
handler.post(new Runnable() {
int i = 0;
@Override
public void run() {
display.setText(wc[i]);
i++;
if (i == wc.length) {
handler.removeCallbacks(this);
} else {
//5 sec
handler.postDelayed(this, 1000 * 5);
}
}
});
答案 1 :(得分:1)
尝试在android中使用处理程序,我认为你正在这样:
String[] wc = {"The","Qucik", "Brown","fox","Jumped"};
int j = 0;
Handler handler = new Handler();
Runnable runit = new Runnable() {
@Override
public void run() {
try{
for (; j < wc.length; j++) {
blinks = wc[j];
final String[] titles = {"" + blinks + ""};
for (int i = 0; i < titles.length; i++) {
display.setText(titles[i]);
}
handler.postDelayed(this,5000);
}
}
catch (Exception e) {
// handle exception
}
}
};
handler.postDelayed(runit, 5000);
答案 2 :(得分:1)
您需要确保每次打勾只拨打TextView.setText()
一次。然后,您可以使用您的方法(CountDownTimer
)或Antrrommet's(Handler
)。使用您的方法,这将类似于:
int counter = 0; // field member, NOT local variable
@Override
public void onTick(long millisUntilFinished) {
display.setText("{" + wc[counter++] + "}");
if (counter == 5) counter = 0;
}
答案 3 :(得分:0)
如果答案有用。请投票:)
final String[] gritArray = getResources().getStringArray(R.array.gritInformation);
//creating new handler allows send and process message
final Handler gritInfoHanlder = new Handler();
//adding runnable to message queque
gritInfoHanlder.post(new Runnable() {
//initializing array position
int tipPosition = 0;
@Override
public void run() {
//set number of tip(randon/another way)
//setting array to textview
gritInfo.setText(gritArray[tipPosition]);
tipPosition++;
//if array exist its length remove callback
if (tipPosition == gritArray.length) {
gritInfoHanlder.removeCallbacks(this);
//delayed handler 10 sec
} else {
gritInfoHanlder.postDelayed(this, 1000 * 10);
}
}
});