android - 为 RelativeLayout 中的膨胀 View 设置参数,但出现 classcastexception

标签 android android-layout

您好,我正在尝试使用 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/

相关文章:

android - 如何停止从 Android 操作系统的消息传递应用程序中删除短信?

android - 如何将datePicker的值设置到EditText中?

android - 如何在 android 方向更改中使用不同的布局

android - Android GridView 或等效项中的不同行高

android - API 21 状态栏后面的工具栏

android - 有没有办法在 android 调试时禁用烦人的设备性能警报?

java - 不同的随机数

Android Camera - 录制视频时预览放大

android - 内容进入alignparentbottom

android - 如何将菜单项设置到操作栏的左侧?