简体   繁体   中英

Setting the rating of the Android Ratingbar

So I'm trying to set the rating of the RatingBar (RB) widget in code during a touch event. Basically, when a user clicks the RB, it has to do some background stuff and then the value of the RB should obviously display the new value.

Okay let me also state that I'm using the RB as a "favourite" button. It's probably not the best thing to use but that doesn't mean I can't, right?

The RB consists of only 1 star. And if a user clicks it, it adds an item to the favourites list and highlights the star. When the user clicks it again, sure enough, the item is removed from the favourites list but the RB does not reset to 0.

favourite_button.setOnTouchListener (new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
  if (event.getAction() == MotionEvent.ACTION_UP) {
    if (_favourited) {
      // do stuff
      favourite_button.setRating(0);
      _favourited = false;
    } else {
      // do stuff
      favourite_button.setRating(1);
      _favourited = true;
    }
  }
  return false;
}});

My code works, and it works well, I just can't see why "unfavouriting" doesn't change the RB back to 0.

So what could be the problem? When I use "setRating(0)" in a setOnRatingBarChangeListener it sure enough sets the rating to 0. But I can't use the setOnRatingBarChangeListener of the RB because one can't "touch" zero stars.

how to set it back to 0 when clicked again?

So @Fondesa has pointed out to me as to why you can't set the rating to 0 in the OnTouch event.

The RatingBar is extended from the SeekBar and the listener actually expects a slide action. Thus the RB can't be set to 0 (or not for this purpose) when there is only one star. The proper widget to use for this type of functionality (no surprise here) is the ToggleButton.

Rather than using on onTouchListener , you should register an OnRatingBarChangeListener . This way, you don't have to worry yourself with the implementation of detecting a touch event and whether that should affect the rating bar, all you need worry about is if the rating was changed:

favourite_button.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
        @Override
        public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
            _favourited = rating > 0;
        }
    });

http://developer.android.com/reference/android/widget/RatingBar.OnRatingBarChangeListener.html

That all being said, I assume you're doing more than just setting a boolean. If you're not, you should just get rid of the boolean completely, and whenever you actually need the value, you can just call favourite_button.getRating()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM