I can't set rating for the RatingBar. My code below. How can I set a default rating for dynamically added RatingBar?
Here is my code.
public class DialogRate extends Activity implements OnRatingBarChangeListener {
...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_layout);
LinearLayout ll_dialog = (LinearLayout) findViewById(R.id.linearLayout_dialog);
final RatingBar rate_bar = new RatingBar(context);
rate_bar.setOnRatingBarChangeListener(this);
rate_bar.setStepSize((float) 0.5);
rate_bar.setMax(5);
rate_bar.setId(1);
rate_bar.setRating(2.0f); // Error occur on this line!
ll_dialog.addView(rate_bar);
}
...
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
// TODO Auto-generated method stub
TextView rate_val = (TextView) findViewById(0);
rate_val.setText(Float.toString(ratingBar.getRating()));
}
Error Stack:
Thread [<1> main] (Suspended)
ActivityThread.performLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 1645
ActivityThread.handleLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 1663
ActivityThread.access$1500(ActivityThread, ActivityThread$ActivityClientRecord, Intent) line: 117
ActivityThread$H.handleMessage(Message) line: 931
ActivityThread$H(Handler).dispatchMessage(Message) line: 99
Looper.loop() line: 123
ActivityThread.main(String[]) line: 3683
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 507
ZygoteInit$MethodAndArgsCaller.run() line: 839
ZygoteInit.main(String[]) line: 597
NativeStart.main(String[]) line: not available [native method]
Close
Sorry guys this error is simple. The TextView in onRatingChanged dynamically created after setRating.
A RatingBar is an extension of SeekBar and ProgressBar that shows a rating in stars. The user can touch/drag or use arrow keys to set the rating when using the default size RatingBar. The smaller RatingBar style ( R.
A user can simply touch, drag or click on the stars to set the rating value. The value of rating always returns a floating point number which may be 1.0, 2.5, 4.5 etc. In Android, RatingBar is an extension of ProgressBar and SeekBar which shows a rating in stars.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have declared Rating bar and set numStars as 5 means it allows maximum number of stars 5 and button.
You can use this code:
rate_bar.setRating(Float.parseFloat("2.0"));
or use this:
rate_bar.setRating(0.0f);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With