Set value in RatingBar

I can’t set a rating for RatingBar. My code is below. How can I set the 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 mistake is simple. The TextView in onRatingChanged is dynamically created after setRating.

+4
source share
1 answer

You can use this code:

 rate_bar.setRating(Float.parseFloat("2.0")); 

or use this:

 rate_bar.setRating(0.0f); 
+28
source

Source: https://habr.com/ru/post/1401989/


All Articles