ImageView change image Android example

How to change the image dynamically in ImageView and button setOnClickListener Android sample.

Main.java

 
ipackage cz.okhelp.my_game;
 
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
 
 
public class Main extends Activity {
private ImageView hImageViewSemafor;
private Button hButton;
 
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        hImageViewSemafor = (ImageView)findViewById(R.id.idImageViewSemafor);
        hButton = (Button) findViewById(R.id.idBtnChangeImage);
        hButton.setOnClickListener(mButtonChangeImageListener);
 
 
 
 
    }
 
    View.OnClickListener mButtonChangeImageListener = new OnClickListener() {
        public void onClick(View v) {
                // setImageResource will change image in ImageView
        	hImageViewSemafor.setImageResource(R.drawable.semafor_green);
 
        }
    };
 
}

main.xml
Put into res/drawable this pictures:
semafor
semafor

 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
 
       <ImageView
            android:src="@drawable/semafor_red"
            android:id="@+id/idImageViewSemafor"
            android:background="#66FFFFFF"
            android:adjustViewBounds="true"
            android:maxWidth="47dip"
            android:maxHeight="91dip"
            android:padding="10dip"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />    
 
</LinearLayout>
This entry was posted in Android Examples Code and tagged , , , . Bookmark the permalink.


Comments are closed.

24,424 views