开发者

Help with getParent() downcast

开发者 https://www.devze.com 2022-12-28 04:50 出处:网络
I\'m learning android/java and have this example code I can\'t get to work: OnRatingBarChangeListener l = new OnRatingBarChangeListener() {

I'm learning android/java and have this example code I can't get to work:

OnRatingBarChangeListener l = new OnRatingBarChangeListener() {
 public void onRatingChanged(RatingBar ratingBar, float rating,
   boolean fromTouch) {
  Integer myPos=(Integer)ratingBar.getTag();
  RowModel model=getModel(myPos);
  model.rating = rating;

  LinearLayout p=(LinearLayout)ratingBar.getParent();
  TextView l=(TextView)p.findViewById(R.id.label);
  l.setText(model.toString());
 }
};

Everything 开发者_如何学Pythonworks except the LinearLayout / getParent() downcast. At runtime it creates a ClassCastException. If I comment out that block of code then everthing works fine. What am I missing?


Well, ratingBar.getParent() doesn't return a LinearLayout. Find out what static type ratingBar.getParent() returns, and use (a reference of ) that type to assign to.

Perhaps you think that ratingBar is-a LinearLayout, and you're confused about Java precedence? Method call operator . has higher precedence than the cast operator (type). It's unlikely, but maybe you meant to do this:

LinearLayout p=( (LinearLayout)ratingBar ).getParent();
0

精彩评论

暂无评论...
验证码 换一张
取 消