سؤال

I have a RatingBar where a user can submit a star number. I don't have a button with it, I want to make it more user friendly and let it submit dynamically.

In the setOnRatingBarChangeListener method, I submit the stars.

Here is quesiton

I'd like to put maybe a 1 second delay before submission, and if the user changes to a different star, reset the timer.

I'm trying to prevent multiple database submissions (or at least limit them).

Is this possible? and how can this be written?

هل كانت مفيدة؟

المحلول

It is definitely possible. An ideal way to do this might be to create a Handler in your class. When the listener is called cancel a Runnable that contains the submission code and post it to run in 1 second. If it is the first time you get the call back the cancel will have no effect but that is fine. Make sure your Runnable is not an anonymous one so that there is only one instance of it so it can be cancelled.

Your question is similar to this one:

How to remove a runnable from a handler object added by postDelayed?

Here is some code:

Handler mHandler = new Handler(Looper.getMainLooper());

Runnable mSubmit = new Runnable() {
    public void run() {
        // Submit to server ...
    }
}

RatingBar.OnRatingBarChangeListener mListener = 
        new RatingBar.OnRatingBarChangeListener() {
    void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
        mHandler.removeCallbacks(mSubmit);
        mHandler.postDelayed(mSubmit, 1000);
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top