ImageView Widget in Android
What you should already KNOW?
|
|
You should be familiar with:
1) Creating, building, and running apps in Android Studio
2) Basics of android widgets
|
|
Explanation: Image View widget is used to insert the image into an activity. There are several attributes of the Image View widget. With the help of android:srcCompat attribute we can set the source of the image we want to insert into an activity.
Example:
Xml File:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="169dp"
app:srcCompat="@mipmap/ic_launcher" />
</RelativeLayout>
In the srcCompat Attribute, physical address of the image is passed.
Java file:
package com.youtubevideoplayer.android.imageview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
public ImageView imageView; // instance of ImageView class is declared as public
public Boolean flag;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView=(ImageView)findViewById(R.id.imageView);
flag=true;
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(flag==true) {
imageView.setImageResource(R.mipmap.ic_launcher_round);//changes the image source
flag=false;
}
else {
imageView.setImageResource(R.mipmap.ic_launcher);//changes the image source
flag=true;
}
}
});
}
}
Image view does not require an java file to be touched (Strictly while working with android studio). But to change the source of the image at the run time of the application, java file is used.
Step by step explanation of the java code:
1) Create an instance variable of ImageView class inside the mainActivity class.
2) Assign the ImageView object to the imageView instance like this inside the onCreate() method.
imageView=(ImageView)findViewById(R.id.imageView);
3) Use method setImageResource of ImageView class to change :
imageView.setImageResource(R.mipmap.ic_launcher_round);
Output Screen: