android - 将 subview 添加到相对布局

标签 android android-relativelayout

虽然我已经解决了很多关于相对布局和以编程方式添加 subview 的问题,但我无法解决这个问题

for (int i=0; i<views; i++) {

    ImageView img = new ImageView(this);
    LayoutParams img_params= new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    img_params.addRule(RelativeLayout.ALIGN_PARENT_LEFT|RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
    relativeLayout.addView(img, img_params);

    TextView textview = new TextView(this);
    LayoutParams text_params= new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    text_params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT|RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
    relativeLayout.addView(textview, text_params);
}

我在下面添加了日志:

06-27 11:16:38.849: E/AndroidRuntime(20595): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

最佳答案

您在循环中一遍又一遍地添加相同的 View 对象。第一次循环运行时,添加了两个 View ,它们现在有了一个父 View 。无法再次添加。

您需要在每次迭代中实例化这些 View 的新实例才能使其正常工作。

关于android - 将 subview 添加到相对布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17335588/

相关文章:

java - 如何从 Google Places API 中删除不需要的地点?

android - 无法获取 facebook sdk 哈希 key 。

安卓预览布局

Android:使用 FrameLayout 和relativeLayout 的屏幕方向

android - 相对布局 : Can't assign a view above a referenced view if margin is involved

android - 无法通过 Android 应用程序访问笔记本电脑的本地主机

android - android 上的词法和语法分析器?

android - 如何将进度条置于布局顶部

android - 拖放持久位置

android - 在列表已经更新和绘制后,如何为单个项目(条目)设置动画?