正如我在我的評論中所說,你可以用Handler
在適當的時間發佈適當的Runnable
對象。
Handler handler = new Handler(); // the handler
String[] text = { "h", "e", "l", "l", "o" }; // the text
TextView[] views = new TextView[5]; // the views 2, 3, 4, 5, 6
當我點擊按鈕1:
的代碼,你可以使用:
button1.setOnClickListener(new OnClickListener() {
int counter = 0; // needed so we know where we are in the arrays
@Override
public void onClick(View v) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
// when this Runnable is done we set the background
// color, the text, update the counter(to update the
// next TextView) and repost the same variable
views[counter].setBackgroundColor(Color.BLUE);
views[counter].setText(text[counter]);
views[counter].setTextColor(Color.WHITE);
counter++;
if (counter < views.length) {
handler.postDelayed(this, 1000); // keep it in the
// arrays bounds
} else {
handler.removeCallbacks(this); // we finished
// iterating over
// the arrays so
// reset stuff and
// remove the
// Runnable
counter = 0;
}
}
}, 1000); // 1 second delay!
}
});
,當我點擊廣場2,則:
這基本上是同樣的事情上面,你只需要確保你不更新引發變化的觀點:
// set as the tag for the 2,3,4,5,6 views their position in the array
for (int i = 0; i < views.length; i++) {
views[i].setTag(i);
views[i].setOnClickListener(mListener);
//...
您可以使用標籤和計數器只更新正確的觀點:
OnClickListener mListener = new OnClickListener() {
int counter = 0;// needed so we know where we are in the arrays
@Override
public void onClick(View v) {
final int whichOne = (Integer) v.getTag(); // gett he views
// position in the
// arrays
// check if we clicked 2
if (counter == whichOne) {
counter++;
}
handler.postDelayed(new Runnable() {
@Override
public void run() {
// on every iteration check to see if we aren't trying
// to update the view that was actually clicked
// if it's the view that was clicked then increment the
// counter
if (counter == whichOne) {
counter++;
}
views[counter].setBackgroundColor(Color.RED);
views[counter].setText(text[counter]);
views[counter].setTextColor(Color.WHITE);
counter++;
if (counter < views.length) {
handler.postDelayed(this, 1000);
} else {
handler.removeCallbacks(this);
counter = 0;
}
}
}, 1000);
}
};
關於單個按鈕的字體和背景更改,它們應該只顯示新值? – Luksprog
@Luksprog是的值存儲在數組中。 – naonweh
您可以輕鬆地使用「Handler」以目標時間間隔發佈文本和後臺更新。 – Luksprog