Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting params for an inflated view inside a RelativeLayout, but getting classcastexception

Hi i'm trying to add a layout programmatically using the inflater (it's a simple TextView). The parent of the inflated view is a RelativeLayout which is in a ScrollView. My problem is that I'm trying to place the new view under its header (which is in the RelativeLayout) using params.addRule and view.setLayoutParams(), but I'm getting a classcast exception: 11-12 13:06:57.360: E/AndroidRuntime(10965): java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.FrameLayout$LayoutParams, even though the parent of the view is clearly a RelativeLayout. Any thoughts?

I'm thinking it's because the RelativeLayout is nested in a scrollview, but I don't understand why it would do this since the direct parent of the view I'm adding is a RelativeLayout.

    _innerLayout = (RelativeLayout) findViewById(R.id.innerRelativeLayout);
    LayoutInflater inflater = (LayoutInflater)this.getLayoutInflater();

    View view = inflater.inflate(R.layout.comments, _innerLayout);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    params.addRule(RelativeLayout.BELOW, R.id.commentsHeader);
    view.setLayoutParams(params);
like image 201
Gak2 Avatar asked Nov 19 '25 05:11

Gak2


1 Answers

If you use a non null View as the root with the inflate() method the View returned will actually be the View passed as the root in the method. So, in your case view is the _innerLayout RelativeLayout which has as a parent a ScrollView, which is an extension of FrameLayout(which will explain the LayoutParams).

So either use the current inflate method, but look for the view in the returned view:

View view = inflater.inflate(R.layout.comments, _innerLayout);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW, R.id.commentsHeader);
(view.findViewByid(R.id.theIdOfTextView)).setLayoutParams(params);

or use another version of inflate()(which doesn't attach he inflated view and manually add it along with proper LayoutParams):

View view = inflater.inflate(R.layout.comments, _innerLayout, false);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW, R.id.commentsHeader);
view.setLayoutParams(params);
_innerLayout.addView(view);
like image 68
user Avatar answered Nov 21 '25 18:11

user



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!