Pages

Thursday, May 5, 2016

Android ImageView Switch Example



MainActivity.java
package kantapp.androidimageviewexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity
{
    ImageView imageView;
    Button button;
    int image_index;
    int[] image_id={
            R.drawable.all_family_of_goku,
            R.drawable.goku,
            R.drawable.dbz,
            R.drawable.goku_family,
            R.drawable.vegito
    };
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        onButtonClick();
    }

    public void onButtonClick()
    {
        imageView=(ImageView)findViewById(R.id.imageView);
        button=(Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                image_index++;
                image_index=image_index%image_id.length;

                imageView.setImageResource(image_id[image_index]);
            }
        });
    }
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="kantapp.androidimageviewexample.MainActivity">

<ImageView
    android:id="@+id/imageView"
    android:layout_width="300dp"
    android:layout_height="300dp"
    android:layout_gravity="center_horizontal"

    android:src="@drawable/all_family_of_goku" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:text="Switch Image" />
</LinearLayout>

Complete project :
https://userscloud.com/zekaubu3voex

only Source code with image:
https://userscloud.com/zekaubu3voex

No comments:

Post a Comment