ImageView example (Switch images)

Learn how to Switch Images in Android

MainActivity CLASS

package com.example.malik.test;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {

private ImageView imageView;
private Button button;
private int current_image_index;
int[] images = {R.drawable.pic1, R.drawable.pic2, R.drawable.pic3, R.drawable.pic4, R.drawable.pic5};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

SwitchImageOnButtonClick();
}

private void SwitchImageOnButtonClick() {
imageView = (ImageView) findViewById(R.id.imageView);
button = (Button) findViewById(R.id.bSwitch);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
current_image_index++;
current_image_index = current_image_index % images.length;
imageView.setImageResource(images[current_image_index]);
}
});
}
}

 

MainActivity XML

<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical”
android:paddingBottom=”@dimen/activity_vertical_margin”
android:paddingLeft=”@dimen/activity_horizontal_margin”
android:paddingRight=”@dimen/activity_horizontal_margin”
android:paddingTop=”@dimen/activity_vertical_margin”
tools:context=”com.example.malik.test.MainActivity”>

 

<ImageView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/imageView”
android:layout_alignParentTop=”true”
android:layout_alignParentLeft=”true”
android:layout_alignParentStart=”true”
android:src=”@android:drawable/alert_dark_frame”
android:scaleType=”fitCenter”
android:layout_alignParentRight=”true”
android:layout_alignParentEnd=”true”
android:layout_above=”@+id/bSwitch” />

<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Switch Image”
android:id=”@+id/bSwitch”
android:layout_alignParentBottom=”true”
android:layout_centerHorizontal=”true” />
</RelativeLayout>

 

Output :

 

pic pic2

 

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.