The image view control of android is very common. It's easy to display pictures. Just set the picture source.
Generally, we use the resources in the APP to achieve this. The original image file is placed in drawable or mipmap under res.
What I want to achieve this time is to let the control display a picture by default. When I click a button, this picture switches to another picture. Moreover, it achieves the effect of switching once every click.
First, add the ImageView control on the interface, and set srcCompat to @ mipmap / IC ﹤ launcher
<ImageView android:id="@+id/imgvwImageChange" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="22dp" android:layout_marginTop="8dp" android:contentDescription="@string/imagechange" app:layout_constraintStart_toEndOf="@+id/btnChangeImage" app:layout_constraintTop_toBottomOf="@+id/edttxtUserName" app:srcCompat="@mipmap/ic_launcher" />
Add another button to trigger the picture switching action.
<Button android:id="@+id/btnChangeImage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:text="@string/changeimage" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/edttxtUserName" />
Implementing button click event monitoring in onCreate function
//Change picture btnChangeImage.setOnClickListener{ if (imgvwImageChange.drawable.current.constantState != resources.getDrawable(R.drawable.tt).constantState){ imgvwImageChange.setImageResource(R.drawable.tt) }else{ imgvwImageChange.setImageResource(R.mipmap.ic_launcher) } }
The way to judge whether a picture is a picture is to use constantState
The two switched pictures are r.mipmap.ic [launcher] and R.drawable.tt.
They put one in mipmap and one in drawable.