In Android, ImageView class is used to display an image file in application. Image file is easy to use but hard to master in Android, because of the various screen sizes in Android devices. An android is enriched with some of the best UI design widgets that allows us to build good looking and attractive UI based application.
Open Android Studio and create a new Project to test ImageView UI Widget.
You can view this blog to know how to create a Project in Android
Your Activity Class (Java File) stored in Src->Your package Name->mainActivity.java
Open activity_main.xml from android resources and remove everything.Drag an Relative Layout and then drag a TextView on Layout in Graphical mode of IDE.
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="dzone.jaipur.myapp1.MainActivity" >
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="114dp"
app:srcCompat="@drawable/images1"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="41dp"
android:layout_marginStart="41dp" />
</RelativeLayout>
Your java File (Android Activity) should look like this..
public class MainActivity extends AppCompatActivity {
ImageView mgi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mgi=(ImageView)findViewById(R.id.imageView);
mgi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mgi.setImageResource(R.drawable.images2);
Toast.makeText(MainActivity.this,"You Cliced on Imageview",Toast.LENGTH_LONG).show();
}
});
}
}
Now Run the Application by upper toolbar green triangle then select your device and get the desired output.
After Clicking on ImageView..
Hope this article will be usefull for you, Happy Coding!!