正如我在评论中所说,您可以通过在所需时间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);
}
};