0

动态添加 ImageView 时,如何在 RelativeLayout 中保留子项的属性?

我有一个自定义 ImageView 我想在运行时添加到一个空的 RelativeLayout(XML 中没有任何内容),我可以添加第一个,然后移动、缩放和旋转它们,它工作正常。当我添加另一个 ImageView 时,所有先前添加的实例都会失去它们的位置和大小,但是当我触摸它们时,它们只会恢复它们的大小,而不是位置。

在我的 ImageView 中,我覆盖了 onDraw 和 onTouch,是否需要覆盖其他内容?也许我必须编写自己的 RelativeLayout 实现?我不会!

这是添加新 ImageView 的伪代码:

create new instance of ImageView
set bitmap
set scaletype
add imageview to the RelativeLayout container

我什至尝试为全新添加的 ImageView 设置标准布局参数,结果相同。我试图根据每个孩子的位置获取边距,并使用 ImgeView.setLayout(l, t, r, b); 重新设置布局;没有成功...

这是 XML RelativeLayout 容器,非常简单,也许太多了?

<RelativeLayout
        android:id="@+id/face_container"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
</RelativeLayout>

您需要更多详细信息来帮助我吗?请问一下,我也可以贴出代码,不过我得先清理一下,明天就可以了,同时请给我一些建议。

4

1 回答 1

0

在 RelativeLayout 中,所有视图位置都与其他视图相关。因此,正如您在 xml 中所做的那样,您应该为每个视图提供相关参数。
在将 imageView 添加到 RelativeLayout 调用之前setLayoutParams(layoutParams)

// Create a new RelativeLayout.LayoutParams instance
RelativeLayout.LayoutParams layoutParams = 
   new RelativeLayout.LayoutParams(
       RelativeLayout.LayoutParams.WRAP_CONTENT,      
       RelativeLayout.LayoutParams.WRAP_CONTENT);

// add roules
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
layoutParams.addRule(.........
layoutParams.addRule(.........

//add params to view
imageView.setLayoutParams(layoutParams);

//add imageview to the RelativeLayout container
yourRelativeLayout.addView(imageView);

在这里查看所有规则。

于 2013-11-02T19:54:35.523 回答