如何在x次后停止postDelayed

时间:2018-03-11 00:16:18

标签: java android multithreading

我正在创建一个动画,随机选择一个从XML字符串数组中提取的字符串。它快速连续地做到这一点,使它看起来像老虎机。我得到了动画,但我不知道如何在x次后停止它。这是我到目前为止所拥有的:

public class MainActivity extends AppCompatActivity {

    TextView locationsTextView;
    Button generateBtn;
    String[] mArray;
    int counter; //<-- This is how I would like to keep track of when handler should stop
    Handler h = new Handler();
    int delay = 50;
    Runnable runnable;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        locationsTextView = findViewById(R.id.locationsTextView);
        generateBtn = findViewById(R.id.generateBtn);
        mArray = getResources().getStringArray(R.array.locations_array);
        locationsTextView.setText("");

        generateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                h.postDelayed(new Runnable() {
                    public void run() {
                        updateTextView();
                        runnable = this;
                        h.postDelayed(runnable, delay);
                    }
                }, delay);
            }
        });
    }

    private void updateTextView() {

        Random random = new Random();
        int maxIndex = mArray.length;
        int generatedIndex = random.nextInt(maxIndex);

        locationsTextView.setText(mArray[generatedIndex]);
    }
}

我认为这样的事情会起作用:

//pseudo code
//Button is clicked
//initialize counter to 0
counter = 0;
//updateTextView method is called repeatedly
counter ++;
if(counter == 50) {
    h.removeCallbacksandMessages(null);
}

我只是不知道我会把它放在代码中。

1 个答案:

答案 0 :(得分:1)

如果我在发布前多花了几分钟,我想我已经明白了。请参阅以下代码:

generateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                counter = 0; //<-- every click, set back to 0
                h.postDelayed(new Runnable() {
                    public void run() {
                        counter++; //<-- increment with every method call
                        updateTextView();
                        runnable = this;
                        h.postDelayed(runnable, delay);
                        if(counter == 50) { //<-- stop after 50
                            h.removeCallbacksAndMessages(null);
                        }
                    }
                }, delay);
            }
        });
    }