您好,我正在尝试使用 inflater 以编程方式添加布局(这是一个简单的 TextView)。膨胀 View 的父级是位于 ScrollView 中的 RelativeLayout。我的问题是我试图使用 params.addRule 和 view.setLayoutParams() 将新 View 放置在其标题下(位于 RelativeLayout 中),但我遇到了类转换异常:11-12 13 :06:57.360: E/AndroidRuntime(10965): java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams 无法转换为 android.widget.FrameLayout$LayoutParams
,即使 View 的父级显然是一个相对布局。有什么想法吗?
我认为这是因为 RelativeLayout 嵌套在 ScrollView 中,但我不明白为什么会这样做,因为我要添加的 View 的直接父级是 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);
最佳答案
如果您使用非 null View
作为 inflate()
方法的根,则返回的 View
实际上是 View
在方法中作为根传递。因此,在您的情况下,view
是 _innerLayout
RelativeLayout
,它的父级是 ScrollView
,它是一个扩展FrameLayout
(将解释 LayoutParams
)。
所以要么使用当前的 inflate 方法,但是在返回的 View 中查找 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);
或使用另一个版本的 inflate()
(它不附加膨胀 View 并手动添加它以及适当的 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);
关于android - 为 RelativeLayout 中的膨胀 View 设置参数,但出现 classcastexception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19936726/