Help with getParent() downcast
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();
精彩评论