Reputation: 9
I have a code with lots of imageview and I would like to dynamically change them on a click. Do I really have to create a condition for every imageview clicked or can I do it simpler? As an example, is there a way to do something like:
@override
public void onClick(View view) {
view.setImageBitmap(null)
}
Upvotes: 0
Views: 65
Reputation: 9
In fact, I found a quite simple way to awnser my problem. first, I put all imageviews in an array and get the id of these in another array. Then I use Arrays.asList(array).indexOf(view.getId());
Pic[0] = (ImageView) findViewById(R.id.imageView1);
Pic[1] = (ImageView) findViewById(R.id.imageView2);
Pic[2] = (ImageView) findViewById(R.id.imageView3);
...
for (int i = 0; i < Pic.length; i++){
id[i] = Pic[i].getId()
}
int u = Array.asList(id).indexOf(view.getId())
Pic[u].Setimagebitmap(null)
Upvotes: 0
Reputation: 411
You can do this if you haven't yet, give onClick
for all the images that you put
<ImageView
android:id="@+id/image1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/image_1"
android:onClick="onClick"
android:layout_weight="1"
android:layout_gravity="center_horizontal"
/>
Then in the activity you can make the Activity implement View.OnClickListener()
and then define its onClick
method as
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.image1:
//Do your thing
break;
case R.id.image2:
//Do your thing
break;
//Add all cases like this
}
}
Let me know if this was helpful to you.
Upvotes: 0