3

嗨,我正在尝试使用充气机以编程方式添加布局(这是一个简单的 TextView)。膨胀视图的父级是一个位于 ScrollView 中的 RelativeLayout。我的问题是我正在尝试使用 params.addRule 和 view.setLayoutParams() 将新视图放置在其标题下(在 RelativeLayout 中),但是我得到了一个类转换异常:11-12 13:06:57.360: E/AndroidRuntime(10965): java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.FrameLayout$LayoutParams,即使view 显然是一个RelativeLayout。有什么想法吗?

我认为这是因为RelativeLayout 嵌套在滚动视图中,但我不明白为什么它会这样做,因为我添加的视图的直接父级是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);
4

1 回答 1

5

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);
于 2013-11-12T18:26:07.307 回答