I have defined an image in my xml file (imageview). I'd like to change it to another image after clicking a button in my activity. How can I do that?
First you implements OnClickListener interface to your activity class.
Java Code
package it.codegen.tbx.my;
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 MytestdroidActivity extends Activity implements OnClickListener {
Button b1;
ImageView iw;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
iw = (ImageView) findViewById(R.id.icon);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == b1)
{
iw.setImageResource(R.drawable.camara);
}
}
}
XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<ImageView android:id="@+id/icon" android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/icon"
/>
<Button android:text="Button" android:id="@+id/button1"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
you should have 2 images in your drawable folder call icon and camara
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With