How to create multiple copies of ImageView object programmatically?

LanguidLegend picture LanguidLegend · Mar 28, 2013 · Viewed 9.4k times · Source

I have an ImageView object, R.id.tile, defined in my XML layout, and what I'm trying to do is create clones of it and place each of them at different coordinates.

This is what I have so far:

    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);
            }
        }
     ...

But when I am debugging it keeps stopping on the line tiles[i] = (ImageView)findViewById(R.id.tile);
with the error "Source not found."

Any ideas?

Answer

sohag picture sohag · Dec 3, 2016

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);
    }
}

app view look like this app view