简体   繁体   中英

Rating bar, how to get the number of stars?

I got an edit text and also a rating bar in my program. I am checking if the user has more than 3 characters in the edit text and for rating bar it should have something greater than 0.5 star (basically to check if they at least clicked on any of them).

    final EditText commentbox = (EditText)findViewById(R.id.comment);
    final RatingBar rating = (RatingBar)findViewById(R.id.rating);
    final Button feedbackbutton = (Button)findViewById(R.id.submit);


    final TextWatcher watcher = new TextWatcher(){

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

            if(commentbox.length() >= 3 && rating.getNumStars() >=0.5){
                feedbackbutton.setEnabled(true);
                feedbackbutton.setBackgroundColor(Color.parseColor("#369742"));
            } else  {
                feedbackbutton.setEnabled(false);
                feedbackbutton.setBackgroundColor(Color.parseColor("#ffcacaca"));
            }


        }

    };
    commentbox.addTextChangedListener(watcher);
    rating.setOnRatingBarChangeListener((this));

So as you can see it has to meet those condition in order for a button to become enabled and also to change its background colour. However soon as I write more than 3 characters in the edit text, the button enables itself and changes its colour. It's not looking for the rating bar condition.

Can someone help me please

To get rating from rating value:

float ratingValue =  rating.getRating();

Add listener :

rating.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {

            @Override
            public void onRatingChanged(RatingBar arg0, float rateValue, boolean arg2) {
                // TODO Auto-generated method stub
                Log.d("Rating", "your selected value is :"+rateValue);
            }
        });
 feedbackbutton.setOnClickListener(new OnClickListener(){  

            @Override  
            public void onClick(View arg0) {  
                //Getting the rating and displaying it on the toast  
                String rating=String.valueOf(rating.getRating());  
                Toast.makeText(getApplicationContext(), rating, Toast.LENGTH_LONG).show();  
            }  

        });

Hope it solves your problem.

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