LanguidLegend
LanguidLegend

Reputation: 53

How to create multiple copies of ImageView object programmatically?

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?

Upvotes: 3

Views: 10439

Answers (2)

sohag
sohag

Reputation: 21

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

Upvotes: 2

Pragnani
Pragnani

Reputation: 20155

ImageView imageview=new ImageView(context);

imageview=yourimageview // copy of your original

For your problem try this

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

Upvotes: -1

Related Questions