Home > Software design >  TextSwitcher switches very quickly on every reload with swiperefresh (Java)
TextSwitcher switches very quickly on every reload with swiperefresh (Java)

Time:11-05

I put a TextSwitcher (fully in xml file) inside a simple method as follow (a TextSwitcher that switches automatically every 2 seconds) and every time I refresh the page using swipeRefresh I don't know why it becomes faster. Why this happen and How can one fix this problem?

    TextSwitcher ts = findViewById(R.id.textswitcher);
    
    swipeRefresh.setOnRefreshListener(() -> {
            showSwitcher(new String[]{"NO WATER", "NO ENERGY"});
            swipeRefresh.setRefreshing(false);
                        });
    ...
    private void showSwitcher(String[] mArray) {
         final int[] idx = {0};
    
                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        idx[0] = ((idx[0]   1) < 2) ? (idx[0]   1) : 0;
                        ts.setText(mArray[idx[0]]);
                        ts.postDelayed(this, 2000);
                    }
                };
    
                ts.postDelayed(runnable, 2000);
    }

swipe refreshing once:

enter image description here

swipe refreshing many times:

enter image description here

CodePudding user response:

I think when you refresh the page, you're adding a new runnable task without removing the old ones. Can you try this.

Runnable runnable;
TextSwitcher ts = findViewById(R.id.textswitcher);

swipeRefresh.setOnRefreshListener(() -> {
    showSwitcher(new String[]{"NO WATER", "NO ENERGY"});
    swipeRefresh.setRefreshing(false);
});

private void showSwitcher(String[] mArray) {
    if (runnable != null) {
        ts.removeCallbacks(runnable);
    }

    final int[] idx = {0};

    runnable = new Runnable() {
        @Override
        public void run() {
            idx[0] = ((idx[0]   1) < 2) ? (idx[0]   1) : 0;
            ts.setText(mArray[idx[0]]);
            ts.postDelayed(this, 2000);
        }
    };

    ts.postDelayed(runnable, 2000);
}
  • Related