如何通过编程创建多个ImageView对象的副本?

3

我有一个ImageView对象,R.id.tile,在我的XML布局中定义,我想要做的是创建它的克隆,并将每个克隆放置在不同的坐标位置。

目前为止,这就是我所拥有的:

    protected void onCreate(Bundle savedInstance)
    {   super.onCreate(savedInstance);
        setContentView(R.layout.board_layout);
        layout = (AbsoluteLayout)findViewById(R.id.board);
        img = (ImageView)findViewById(R.id.tile);
        View[] tiles = new ImageView[9];
        for (int i = 0; i<tiles.length; i++) {
            tiles[i] = (ImageView)findViewById(R.id.tile);
        }

        for(int i=0; i<3; i++){
            for(int j=0; j<3; j++){
                tiles[i+j].setX((float) 32*2*i);
                tiles[i+j].setY((float) 34.39*2*j);
            }
        }
     ...

但是当我调试时,它总是停在这一行上:tiles[i] = (ImageView)findViewById(R.id.tile);
并出现错误信息"源代码未找到。"

有什么想法吗?


你为什么要使用原始ImageView的克隆而不是创建新的ImageView并将它们的图像设置为相同的呢?我认为后一种方法会更容易。然后,你可以调用layout.addView(tiles[i]);将新的ImageView添加到你的布局中。 - FoamyGuy
1
@FoamyGuy 可能他不想为所有的属性或样式(如高度、宽度等)编写程序来设置原始 ImageView 获取的所有属性或样式。 - Pragnani
1
@Pragnani 可能是这样,如果是这种情况,他可以在其on layout.xml文件中声明ImageView,然后使用LayoutInflater创建新的ImageView,这将使它们都预设为所需的配置。 - FoamyGuy
@FoamyGuy 是的...同意.. - Pragnani
2个回答

2

activity_main.xml

<LinearLayout
    android:id="@+id/linear"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">
</LinearLayout>

MainActivity.java

ImageView iv;
LinearLayout linear;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    linear = new LinearLayout(this);
    linear = (LinearLayout)findViewById(R.id.linear);

    for(int i=1;i<10;i++)
    {
        iv = new ImageView(this);
        iv.setImageResource(R.drawable.plus);
        iv.setPadding(0,0,0,20);
        linear.addView(iv);
    }
}

应用程序视图如下所示:应用程序视图


-1
ImageView imageview=new ImageView(context);

imageview=yourimageview // 复制你的原始图像视图

针对你的问题,请尝试这个方法

View[] tiles = new ImageView[9];
ImageView testview= (ImageView)findViewById(R.id.testview);

for (int i = 0; i<tiles.length; i++) {
            tiles[i] = new Imageview(context);
        }

我使用了这些更改,没有出现错误(耶!),但是在布局中只有tiles的第9个实例(最后一个元素)显示出来。我猜这是因为tiles数组的每个元素都指向同一个对象? - LanguidLegend
@AdamChoate 是的...使用单独的布局并在其中放置一个ImageView...然后填充ImageView以获取其副本..并使用该图像..就像FoamGuy建议的那样。 - Pragnani
我需要为每个ImageView实例创建一个新的布局吗?你能给我演示一下吗? - LanguidLegend
感谢您的快速回复 :) 无论如何,我已经开了一个新问题,关于如何填充多个视图对象: 如何在布局上填充ImageView对象的新副本? - LanguidLegend
4
代码不太合理。您重复为tiles[i]赋值,语句"tiles[i] = new Imageview(context);" 不应该有任何效果。 - M. Usman Khan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接